本文提供三种方法对简单数组去重, 其中本人最喜欢 set 方法, 因其简单代码量小.
- const array = ['', 1, 2, '','', 3];
- // 1: "Set"
- [...new Set(array)];
- // 2: "Filter"
- array.filter((item, index) => array.indexOf(item) === index);
- // 3: "Reduce"
- array.reduce((unique, item) =>
- unique.includes(item) ? unique : [...unique, item], []);
- // RESULT:
- // ['', 1, 2, 3];
- Set
Set 是 ES6 中引入的新数据对象. 因为 Set 只允许您存储唯一值. 创建 Set 时, 它将删除所有重复的值.
Set 对象允许你存储任何类型的唯一值, 无论是原始值或者是对象引用.
使用 Set 时, 有两个步骤:
首先, 我们 Set 通过传递数组来创建一个新数组. 因为 Set 仅允许唯一值, 所以将删除所有重复项.
现在重复项不见了, 我们将使用散布运算符将其转换回数组 ...
- const array = ['', 1, 2, '','', 3];
- // Step 1
- const uniqueSet = new Set(array);
- // Set { '', 1, 2, 3 }
- // Step 2
- const backToArray = [...uniqueSet];
- // ['', 1, 2, 3]
另外, 您也可以使用 Array.from 将转换 Set 为数组:
- const array = ['', 1, 2, '','', 3];
- Array.from(new Set(array));
- // ['', 1, 2, 3]
- Filter
为了理解此方式, 我们可以需要了解 indexOf 和 filter 这两种方法.
indexOf
indexOf 方法返回从数组中找到的所提供元素的第一个索引.
- const array = ['', 1, 2, '','', 3];
- array.indexOf(''); // 0
- array.indexOf(1); // 1
- array.indexOf(2); // 2
- array.indexOf(3); // 5
该 filter() 方法创建一个新的元素数组, 这些数组可以通过我们提供的条件. 换句话说, 如果元素通过并返回 true, 它将被包含在过滤后的数组中. 并且任何失败或返回的元素 false 都将不在过滤后的数组中.
所以 filter 的最终实现代码是:
- const array = ['', 1, 2, '','', 3];
- array.filter((item, index) => array.indexOf(item) !== index);
- // ['','']
- Reduce
该 reduce 方法用于减少数组的元素, 并根据传递的某些 reducer 函数将它们组合为最终数组.
在这种情况下, 我们的 reducer 函数将检查最终数组是否包含该项. 如果没有, 则将该项目推入我们的最终数组. 否则, 跳过该元素并按原样返回我们的最终数组 (基本上跳过该元素).
- const array = ['', 1, 2, '','', 3];
- array.reduce((unique, item) => {
- console.log(
- // a. Item
- item,
- // b. Final Array (Accumulator)
- unique,
- // c. Condition (Remember it only get pushed if this returns `false`)
- unique.includes(item),
- // d. Reducer Function Result
- unique.includes(item) ? unique : [...unique, item],
- );
- return unique.includes(item) ? unique : [...unique, item]
- }, []); // The initial value of our Accumulator is an empty array
- // RESULT:
- // ['', 1, 2, 3];
来源: http://www.mzh.ren/es6-3-ways-to-remove-array-duplicates.html