js/es6获取数组重复字段并且得到重复的下标位置
使用快捷去重的函数
set / reduce
通常的数组格式
let a = [
{id:1,val:2},
{id:2,val:3},
{id:1,val:4}
]
const b = a.map((e)=>{
retrun e.id
})
const b = a.map((e)=> e.id )
// 打印
// console.log(b)
// b = ['1','2','1']
es6
Set
文档 具体案例请看文档
// 去除数组的重复成员
[...new Set(array)]
reduce
函数
array.reduce(function(accumulator, currentValue, currentIndex, arr), initialValue);
accumulator: 必需。累计器
currentValue: 必需。当前元素
currentIndex: 可选。当前元素的索引;
arr: 可选。要处理的数组
initialValue: 可选。传递给函数的初始值,相当于accumulator的初始值
let list = '123123'.split('')
const newList = list.reduce((pre, cur) => {
return pre.includes(cur) ? pre : pre.concat(cur)
}, [])
下面为
reduce
找到重复字段与存在的下标位置
const list = 'abcabcabc'.split('')
let i = 0
const pre = list.reduce((pre, cur) => {
if (pre[cur]) {
pre[cur].push(i)
} else {
pre[cur] = [i]
}
i++;
return pre
}, {})
console.log(pre)
// {
// a: [0, 3, 6],
// b: [1, 4, 7]
// c: [2, 5, 8]
// }
- 具体的思路a b c 分别是数组,
- 如果是他的长度是1 就代表没有重复,
- 如果大于1就代表存在重复,而且知道他的下标是多少
然后使用 for in 来遍历对象
for (let key in obj) {
console.log(key :对象名 obj[key] 为重复数组的下标)
}