let arr = [
{ id: 1, name: 'Tom' },
{ id: 2, name: 'Jerry' },
{ id: 1, name: 'Tom' },
{ id: 3, name: 'Mickey' },
{ id: 2, name: 'Jerry' }
];
// 方法一
const uniqueArr = (arr, key='id') => arr.reduce((prev, cur) => {
if (!prev.some(item => item[key] === cur[key])) {
prev.push(cur);
}
return prev;
}, []);
// 方法二
const duplicateById = (list, uniqueKey='id') => [...list.reduce((prev, cur) => prev.set(cur[uniqueKey], cur), new Map()).values()]
// 输出
console.log(uniqueArr(arr))
console.log(duplicateById(arr))
[
{
"id": 1,
"name": "Tom"
},
{
"id": 2,
"name": "Jerry"
},
{
"id": 3,
"name": "Mickey"
}
]
网友评论