JavaScript

How to remove duplicate array elements with JavaScript

November 18, 2021

How to remove duplicate array elements with JavaScript

In this article, we’ll learn how to remove duplicate array elements in the JavaScript language as efficiently as possible.

remove duplicate array elements cover

Hey you programmer, okay? Let’s learn something new!

The array can often be dirty, with duplicate elements or even data that we won’t use

Then, we need to remove duplicate elements, transform the array data and then make use of it

In the JavaScript language we can elegantly do this removal, using features added in ES6, check it out:

let array = [1,2,3,4,4,5,6,7,8,6,5,4,3,2,1];

let newArray = [...new Set(array)];

console.log(newArray); // [1, 2, 3, 4, 5, 6, 7, 8]

Let’s now see in detail what happened in these lines of code

We programmed a Set object, which can only contain unique elements in it.

Combining the spread syntax, this allows iterating over the values of the original array

Finally, we create an array with the square brackets

And this way we can only have single elements in the array, solving our problem

This is the most elegant and fastest way to achieve this result.

We use advanced features of the language, and we can do with any type of data without worries

Conclusion

We learned in this article a way to have an array with single elements in the JavaScript language

We use the Set object together with the spread to reach this result

Do you want to improve your JavaScript skills? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x