JavaScript数组过滤-删除相似数字

// 需求:删除相似数字,让数组中任意两个数字的差值都>=某个值

/**
 * 数字过滤
 * @param numArr 数字集合
 * @param difference 差值
 * @returns 
 */
const digitalFilter = (numArr: number[], difference: number) => {
    for (let i = 0; i < numArr.length; i++) {
        for (let j = i + 1; j < numArr.length; j++) {
            if (Math.abs(numArr[i] - numArr[j]) < difference) {
                numArr.splice(j, 1)
                j--
            }
        }
    }
    return numArr
}

// 调用
const result = digitalFilter([1, 101, 102, 203, 5, 667, 7, 78, 34, 45, 78, 123, 1, 213, 123, 123, 435, 1010, 546, 1000, 8], 100);

// 输出结果: [1, 101, 203, 667, 435, 1010, 546]
console.log(result);

你可能感兴趣的:(JavaScript数组过滤-删除相似数字)