new Set()
ES6 新增了 Set 这一数据结构,类似于数组,但 Set 的成员具有唯一性
基于这一特性,就非常适合用来做数组去重了
function distinct(a, b) {
return Array.from(new Set([...a, ...b]))
}
//简写为
function distinct(a, b) {
return [...(new Set([...a, ...b]))]
}
//单个数组可用
function distinct(a) {
return [...(new Set([...a]))]
}
for...of + Object(这个是速度最快的)
这个方法我只在一些文章里见过,实际工作中倒没怎么用
首先创建一个空对象,然后用 for 循环遍历
利用对象的属性不会重复这一特性,校验数组元素是否重复
function distinct(a, b) {
let arr = a.concat(b)
let result = []
let obj = {}
for (let i of arr) {
if (!obj[i]) {
result.push(i)
obj[i] = 1
}
}
return result
}如果用for...of +Obj 这个方法是会相同对象名称也会去重
去除数组中相同id的对象
let imageList = [{id:1,name:"小小"},{id:1,name:"小小2"},{id:2,name:"小小"}];
var obj = {};
imageList = imageList.reduce(function (item, next) {
obj[next.id] ? '' : obj[next.id] = true && item.push(next);
return item;
}, []);