1. 数组去重
let arr = [1, 3, 5, 6, 9, 1, 3, 2];
new Set(arr) // 去重
Array.from(new Set(arr)) // 将伪数组转换成真数组 并去重
2. 数组对象去重
方法一:
let arr = [{
key: 'R',
code: 520
},
{
key: 'o',
code: 521
},
{
key: 'y',
code: 522
},
{
key: 'a',
code: 666
},
{
key: 'l',
code: 668
},
{
key: 'oo',
code: 521
}];
const codeArr = []; // 通过code来判断重复项
arr.forEach(v => codeArr.push(v.key));
const newArr = []; // 去重后的新数组
const newCode = new Set(keyArr); // code去重
newCode.forEach(item =>{
const index = codeArr.findIndex(item2 => item2 === item);
newArr.push(arr[index]);
})
console.log('去重后的数组:', newArr);
方法二: 利用reduce
let arr = [{
key: 'R',
code: 520
},
{
key: 'o',
code: 521
},
{
key: 'y',
code: 522
},
{
key: 'a',
code: 666
},
{
key: 'l',
code: 668
},
{
key: 'oo',
code: 521
}];
const hash = {};
const newArray = arr.reduce((item, next)=>{
hash[next.code] ? '' : hash[next.code] = true && item.push(next);
return item;
},[])
console.info('去重后的数组:', newArray);