js 数组去重

1.for循环
const arr = [{name:‘小明’},{name:‘小红’},{name:‘小红’},{name:‘小红’}];
const obj = {};
const newArr = [];
for(let i=0;i<arr.length;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);

posted @ 2022-05-18 15:34  向前、向前  阅读(36)  评论(0编辑  收藏  举报