关于javascript:JavaScript数组过滤删除相似数字

40次阅读

共计 455 个字符,预计需要花费 2 分钟才能阅读完成。

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

/**
 * 数字过滤
 * @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);

正文完
 0