How to remove duplicates from a JavaScript array
If you have an array with duplicate values in JavaScript, you may be wondering how to remove those duplicates effectively. This can be done using the Set data structure, which was introduced in ES6 in 2015.
Suppose you have an array that contains various primitive values, such as numbers or strings. Some of these elements may be repeated. For example:
1 | const list = [1, 2, 3, 4, 4, 3] |
To remove the duplicate values from this array and create a new array with unique values, you can use the following code:
1 | const uniqueList = [...new Set(list)] |
After executing this code, the variable uniqueList
will contain a new array without any duplicate values. In the case of our example, uniqueList
would be [1, 2, 3, 4]
.
So, how does this code work? The Set
is a special data structure that only allows unique values. By initializing a Set
with a destructured array (using the ...
operator before new Set()
), the duplicate values are automatically removed. Finally, we convert the Set
back into an array by wrapping it with square brackets []
.
It’s important to note that this method works with any values that are not objects, such as numbers, strings, booleans, and symbols. If you have an array containing objects, you will need to use a different approach to remove duplicates.
This technique can be useful in scenarios where you need to work with unique values from an array, such as when performing calculations or comparisons. By removing duplicates, you can simplify your code and improve its efficiency.
Tags: JavaScript, array, duplicates, Set, ES6