js 数组对象去重的几种方式

1.for循环
const arr = [{name:‘小明’},{name:‘小红’},{name:‘小红’},{name:‘小红’}];
const obj = {};
const newArr = [];
for(let i=0;i if(!obj[arr[i].name]){
newArr.push(arr[i]);
obj[arr[i].name] = true;
}
}
console.log(newArr);

2.new Set实现数组去重
const arr = [1,2,3,3,3,3,3,2,2,3];
//const newArr = […new Set(arr)];//通过ES6的new Set进行数组去重:
console.log(newArr);

//通过ES6的new Set进行对象数组去重
let arr2=[{a:‘1’,b:‘q’},{a:‘1’,b:‘q’},{a:‘2’,b:‘b’}]
const newArr = […new Set(arr2.map(e=>JSON.stringify(e)))].map(e=>JSON.parse(e))
console.log(newArr);
3.filter 实现数组去重
const arr = [1,2,3,3,3,3,3,2,2,3];
//const newArr = arr.filter((it,index,list)=>list.indexOf(it) === index)
console.log(newArr);

你可能感兴趣的:(js,前端)