js查找数组的重复项和对应的下标
处理逻辑,每一项都跟后面的每一项进行对比,所以是要遍历2次的
function getSameItem() {
var arr = [12, 12, 9, 12, 4, 5, 4, 4, 3, 5, 3] // 要查找的数组
var obj = {
} // 重复项组成的对象
arr.forEach((item, index) => {
arr.forEach((item1, index1) => {
// 每一项要后面的每一项进行对比
if (index1 > index && item == item1) {
if (!obj[item]) {
// 设置初始数组
obj[item] = []
obj[item].push(index)
obj[item].push(index1)
} else {
obj[item].push(index)
obj[item].push(index1)
}
}
})
})
Object.keys(obj).forEach((item, index) => {
obj[item] = [...new Set(obj[item])] //去掉重复下标,有重复下标是因为push了index和index1
if(obj[item].length > 1) {
console.log(有重复项:, item, 下标为:, obj[item], 重复数量为:, obj[item].length,=======)
}
})
}
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
Spark随机森林之多分类模型
