How to remove duplicate elements from an array in javascript?

In this article, We’ll see how to remove a duplicate element from an array in javascript?

In ES6, we’ll use new Set data structure to remove a duplicate elements from an array.

Befor using the new Set data structure, we’ll read about its decription.

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set’s collection.

Using the Set constructor and the spread syntax:

var array          =  [2, 5, 9, 5, 9];
const filter_arr   =  [... new Set(array)];
console.log(filter_arr); // Output [2, 5, 9]

In ES5, we can use the native filter method to get a unique values from an array.

var array = [2, 5, 9, 5, 9];
var uniqueValues = [];
$.each(array, function(i, el){
    if($.inArray(el, uniqueValues) === -1) uniqueValues.push(el);
console.log(uniqueValues); // Output [2, 5, 9]

That’s it!. Please share your thoughts or suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *