这是从数组中筛选出重复项并仅返回唯一值的三种方法。我最喜欢的是使用Set,因为它是最短和最简单的。
1.使用Set
首先让我解释一下Set:Set是ES6中引入的新数据对象。因为Set仅允许您存储唯一值。传递数组时,它将删除所有重复的值。
好的,让我们回到我们的代码并分析正在发生的事情。有两件事发生:首先,我们Set通过传递数组来创建一个新数组。由于Set仅允许唯一值,因此将删除所有重复项。
现在重复项不见了,我们将使用扩散运算符...将其转换回数组const array = ['i',1,2,'i','i',3];
// Step 1
const uniqueSet = new Set(array);
const newArrary = [...uniqueSet];
使用Array.from转换Set为数组
另外,您也可以使用Array.from转换Set为数组:const array = ['i',1,2,'i','i',3];
Array.from(new Set(array));
2:使用filter
为了理解此选项,让我们看一下这两种方法的作用:indexOf和filter。
indexOf
该indexOf方法返回从数组中找到的所提供元素的第一个索引。const array = ['i',1,2,'i','i',3];
array.indexOf('i'); //0
array.indexOf(1); //1
array.indexOf(2); //2
array.indexOf(3); //5
filter
该filter()方法创建一个新的元素数组,这些数组可以通过我们提供的条件。换句话说,如果元素通过并返回true,它将被包含在过滤后的数组中。并且任何失败或返回false的元素都将不在过滤后的数组中。
让我们进入并逐步了解遍历数组时发生的情况。const array = ['i',1,2,'i','i',3];
array.filter((item, index) => {
console.log(item,index,array.indexOf(item),arrary.indexOf(item) === index,);
return array.indexOf(item) === index
});
下面是上面显示的console.log的输出。重复项是索引与indexOf不匹配的地方。因此,在这些情况下,条件将为false,并且不会包含在我们的过滤数组中。
检索重复值
我们还可以使用filter方法从数组中检索重复的值。我们可以这样简单地调整条件来做到这一点:const array = ['i',1,2,'i','i',3];
array.filter((item,index)=>array.indexOf(item)!==index);
3:使用reduce
该reduce方法用于减少数组的元素,并根据传递的某些reducer函数将它们组合为最终数组。
在这种情况下,我们的reducer函数将检查最终数组是否包含该项。如果没有,则将该项目推入我们的最终数组。否则,跳过该元素并按原样返回我们的最终数组(实质上跳过该元素)。
Reduce总是很难理解,所以让我们也进入每种情况并查看输出:const array = ['i',1,2,'i','i',3];
array.reduce((unique,item) => {
console.log(item, unique, unique.includes(item), unique.includes(item)?unique:[...unique,item],);
return unique.includes(item)?unique:[...unique,item]
}, []);