js/es6获取数组重复字段并且获取下标位置,去重/查重/重复下标

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] 为重复数组的下标)
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值