During the project process, sometimes it is necessary to deduplicate the received data:
1. If it is pure data with only one layer of data structure, I usually use ES6's new Set method to remove duplicates:
let arr = [1,4,5,7,3,6,1,4];
let newArr = Array.from(new Set(arr));
console.log(newArr);
//[1,4,5,7,3,6]
2. But in real projects, we rarely encounter the above arrays, so when encountering objects in the array, I generally use the following method to deduplicate:
methods:{
handleDuplicateRemoval(list){
let userList = [];
let hash = {};
userList = list.reduce((preVal, curVal) => {
hash[curVal.name] ? '' : hash[curVal.name] = true && preVal.push(curVal);
return preVal
}, []);
return userList;
},
getListData(){
let list = [
{
id:1,
name:'张三',
companyId:666
},
{
id:2,
name:'李四',
companyId:222
},
{
id:3,
name:'张三',
companyId:888
}
];
}
let listData = this.handleDuplicateRemoval(list);
//listData为根据name去重之后新的数组
}