博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何从JavaScript数组中删除重复项
阅读量:2514 次
发布时间:2019-05-11

本文共 1159 字,大约阅读时间需要 3 分钟。

Let’s say you have an array containing a series of primitive values, for example numbers or strings.

假设您有一个包含一系列原始值的数组,例如数字或字符串。

Some of those elements are repeated.

这些元素中有一些是重复的。

Like in this example:

像这个例子一样:

const list = [1, 2, 3, 4, 4, 3]

We can generare a new array containing the same values, without the duplicates, in this way:

我们可以通过这种方式生成一个包含相同值但没有重复值的新数组:

const uniqueList = [...new Set(list)]

uniqueList will now be a new array with the values [1, 2, 3, 4] in it.

现在, uniqueList将是一个新数组,其中包含[1, 2, 3, 4]值。

How does this work?

这是如何运作的?

Set is a new data structure, introduced in ES6 in 2015, and its main characteristic is to be a container for data that can’t be repeated in the same set. .

Set是一种新的数据结构,于2015年在ES6中引入,其主要特征是成为无法在同一集合中重复的数据的容器。 。

By initializing a Set with a destructured array (see the ... operator before new Set()), we pass values and Set automatically removes the duplicates. Then we convert it to an array by wrapping it into square brackets [].

通过使用解构数组初始化Set(请参阅new Set()之前的...运算符),我们传递值,并且Set自动删除重复项。 然后,通过将其包装在方括号[] ,将其转换为数组。

This method works with anything that’s not an object: , , booleans, .

此方法适用于所有非对象: , ,布尔值, 。

翻译自:

转载地址:http://ihmgb.baihongyu.com/

你可能感兴趣的文章
linux下c语言程序、头文件h、Makefile的例子
查看>>
In function `main': testpcre.c:(.text+0x93): undefined reference to `pcre_compile' testpcre.c:(.tex
查看>>
机试题 abc
查看>>
机试题 求root(N,k)
查看>>
机试题:今年的第几天?
查看>>
机试题:递推数列
查看>>
机试题:最大序列和
查看>>
内存的分区?
查看>>
机试题:N的阶乘(N很大时)
查看>>
机试题:最小花费
查看>>
循环语句中 i++和++i有什么区别吗
查看>>
机试题 10进制2进制逆序数
查看>>
机试题:谁是你的潜在朋友?
查看>>
密码翻译
查看>>
机试题:最简真分数
查看>>
中位数
查看>>
机试题:小白鼠排队
查看>>
约瑟夫环问题思路解读
查看>>
机试题:大整数的因子
查看>>
关于Java BigInteger 踩坑记录
查看>>