记录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引用类型:
// 数据 let 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" }]; // 根据name值去重 const hash = {}; arr = arr.reduce((acc, curr) => { hash[curr.name] ? '' : hash[curr.name] = true && acc.push(curr); return acc; }, []); console.log(arr);