[译]ES6数组去重的3种方法

[广告:最高 ¥2000 红包]阿里云服务器、主机等产品通用,可叠加官网常规优惠使用 | 限时领取

原文:How to Remove Array Duplicates in ES6 | SamanthaMing.com

本文提供三种方法对简单数组去重,其中本人最喜欢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时,它将删除所有重复的值。

PS:集合(set)在任何语言中表现都是一样的。

集合是指具有某种特定性质的具体的或抽象的对象汇总而成的集体。

集合具有互异性: 一个集合中,任何两个元素都认为是不相同的,即每个元素只能出现一次

Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。

使用Set时,有两个步骤:

  1. 首先,我们Set通过传递数组来创建一个新数组。因为Set仅允许唯一值,所以将删除所有重复项。
  2. 现在重复项不见了,我们将使用散布运算符将其转换回数组 ...
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

为了理解此方式,我们可以需要了解indexOffilter这两种方法。

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];

码中人 微信公众号
分类: 未分类

关注微信公众号

码中人 微信公众号