引言
在实际开发中,偶尔会遇到数组去重的需求,本文介绍几个去重方法。
filter 去重
最简单的去重方式是利用 filter 和 indexOf 方法。
const arr = ['hello', 'world', 'hello', 100, 100, '100'];const rmDup = (elem, index, arr) => arr.indexOf(elem) === index;const newArr = arr.filter(rmDup);console.log(newArr); // ["hello", "world", 100, "100"]
indexOf 方法,总是查找元素第一次出现的位置。
这个方法适用于数组元素都是基本值类型的情况,如果出现重复对象就不好使了。
const arr = ['hello', 'world', 'hello', 100, 100, '100', {a: 100}, {a: 100}];const rmDup = (elem, index, arr) => arr.indexOf(elem) === index;const newArr = arr.filter(rmDup);console.log(newArr); // ["hello", "world", 100, "100", {…}, {...}]
includes 去重
includes() 方法返回一个布尔值,表示数组是否包含给定的值。
const arr = [ 'hello', 'world', 'hello', 100, 100, '100', { a: 100 }, { a: 100 }, true, true, false, false];const result = [];for (let index = 0; index < arr.length; index++) { if (!result.includes(arr[index])) { result.push(arr[index]); }}console.log(result);
Set + Array.from 去重
Set 是 ES6 新增的数据结构。类似于数组,但不是数组,成员的值唯一,不存在重复值的成员,但对象会重复,因为引用不同。
const mySet = new Set(['hello', 'world', 'hello', 100, 100, '100', {a: 100}, {a: 100}]);console.log(mySet); // {"hello", "world", 100, "100", {…}, {...}}
Array.from 是 ES6 新增的方法用于将类数组对象和可遍历的对象转换为真正的数组。可以利用 Set 和 Array.from 方法快速给数组去重,但同样无法去除重复的对象。
const arr = Array.from(mySet);console.log(arr); // ["hello", "world", 100, "100"]
也可以用 Set + 扩展运算符 ,但同样不支持对象去重。
const mySet = new Set(['hello', 'world', 'hello', 100, 100, '100', {a: 100}, {a: 100}]);const result = [...mySet];console.log(result); // ["hello", "world", 100, "100", {…}, {…}]
HashTable 去重
JavaScript 的对象天生就是 HashTable 。它以一种 key: value 的形式保存数据。
对象属性的键是 string 类型,无法区分 number 类型的属性。
const hashTable = {};hashTable[1] = "hello";hashTable['1'] = "world";console.log(hashTable); // {1: "world"} ,无法区分
利用 JSON.stringify() 方法将键转换为 JSON 字符串,就可以区分了。
console.log(JSON.stringify('1')); // '1' 相当于 '1','1' 当做整体转换为字符串console.log(JSON.stringify(1)); // 1const hashTable = {};hashTable[JSON.stringify(1)] = "hello";hashTable[JSON.stringify('1')] = "world";console.log(hashTable); // {1: "hello", "1": "world"}
可以利用 HashTable 给数组去重,原理是将数组元素变成对象的键,然后利用 filter() 方法过滤返回。
这个方法可以去重对象了,因为对象被变成了字符串类型的键。
function rmDup(arr) { const hashTable = {}; const filterHash = (elem) => { // 将数组元素变成 hashTable的键 // 如 hashTable['{a: 100}'] const key = JSON.stringify(elem); // hashTable['{a: 100}'] 它的值根据下面代码设置 // 只有 true 和 false const result = hashTable[key]; if (result) { // 如果是 true 代表已经存在了,就不会被 filter 方法收集 return false; } else { // 如果是 false 代表还没有这个值 // 它会被 filter 收集,然后将这个 hashTable['键']的值为 true // 例如,第 1 个元素 'hello' 传入 filter 方法,hashTable['hello'] 还没有 // 于是就把 hashTable['hello'] = true ,当第 3 个元素传入 filter 方法时 // 它的值还是 'hello' ,于是 result = true ,就会运行 if 块,从而不会被 // filter 收集,达到去重的目的 hashTable[key] = true; return true; } } const filterArr = arr.filter(filterHash); return filterArr;}const myArr = rmDup([ 'hello', 'world', 'hello', 100, 100, '100', {a: 100}, {a: 100}, ['a', 'b'], ['a', 'b'], true, true, false, false,]);console.log(myArr); // ["hello", "world", 100, "100", {a: 100}, 'a', 'b', true, false]
for...of + HashTable 去重
这个方法的性质和上面的性质一样,只不过利用 for...of 循环实现。
function rmDup(arr) { const hash = {}; const result = []; for (let elem of arr) { const key = JSON.stringify(elem); if (!hash[key]) { result.push(elem); hash[key] = true; } } // arr.forEach((elem) => { // const key = JSON.stringify(elem); // if (!hash[key]) { // result.push(elem); // hash[key] = true; // } // }) // for(let index = 0; index < arr.length; index++) { // const key = JSON.stringify(arr[index]), // elem = arr[index]; // if (!hash[key]) { // result.push(elem); // hash[key] = true; // } // } return result;}const arr = [ 'hello', 'world', 'hello', 100, 100, '100', { a: 100 }, { a: 100 }, ['a', 'b'], ['a', 'b'], true, true, false, false];console.log(rmDup(arr));
相关推荐
了解箭头函数,请阅读文章:《理解 JavaScript 箭头函数》
了解 filter() 方法,请阅读文章:《简单实用,JavaScript 的 8 个数组遍历方法》
文章图片来源于网络,若有侵权行为,请在后台与我联系。