简单数组
const repeatArray = [1,2,3,1];
const noRepeatArray = Array.from(
new Set(repeatArray)
);
console.log(noRepeatArray); //[1,2,3]
没啥好说的, ES6的new Set(Array)将数组转化为无重复key的Object, 再Array.from转回数组.
含对象数组
const repeatIdArray = [
{id: 1},
{id: 2},
{id: 1}
];
let noRepeatIdArray = repeatIdArray.reduce(
(current, next) => {
if(!current[next.id]) {
current[next.id] = next;
}
return current;
}, {}
)
noRepeatIdArray = Object.values(noRepeatIdArray);
console.log(noRepeatIdArray); // [{id:1}, {id:2}]
array.reduce((a, b) => a+b )取和应该都很熟悉, 其实应该写成array.reduce((a, b) => a+b, 0), (a, b) => a+b, 作为第一个参数, 0 作为起始参数, 也就是上面用到的current.
此处用了个{}作为起始current, 以id值作为key实现去重.然后Object.value()处理一下返回数组.
灵活运用的话还可以根据对象的其他属性筛选去重等等...