阅读 6006

es6数组去重(连重复的对象也可以去掉)

1,去除简单类型

//ES6中新增了Set数据结构,类似于数组,但是 它的成员都是唯一的 ,其构造函数可以接受一个数组作为参数,如:
let array = [1, 1, 1, 1, 2, 3, 4, 4, 5, 3];
 let set = new Set(array);
 console.log(set);
 // => Set {1, 2, 3, 4, 5}

//ES6中Array新增了一个静态方法Array.from,可以把类似数组的对象转换为数组,如通过querySelectAll方法得到HTML DOM Node List,以及ES6中新增的Set和Map等可遍历对象,如: let set = new Set();
 set.add(1).add(2).add(3);
 let array = Array.from(set);
 console.log(array);
 // => [1, 2, 3]

       //于是,现在我们可以用一行代码实现数组去重了:
      let array = Array.from(new Set([1, 1, 1, 2, 3, 2, 4]));
      console.log(array);
      // => [1, 2, 3, 4]复制代码

2,去除引用类型

var arr = [{
    "name": "ZYTX",
    "age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
    "gender": "AAAAAA.doc"
}, {
    "name": "ZYTA",
    "age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
    "gender": "BBBBBB.doc"
}, {
    "name": "ZDTX",
    "age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
    "gender": "CCCCCC.doc"
}, {
    "name": "ZYTX",
    "age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
    "gender": "AAAAAA.doc"
}];
var hash = {};
arr = arr.reduce(function(item, next) {
    hash[next.name] ? '' : hash[next.name] = true && item.push(next);
    return item
}, [])
console.log(arr);复制代码


评论