Search code snippets, questions, articles...

Remove duplicate items from array in Javascript

We are going to explain methods with code examples in this post that can be used to remove duplicate values from an array using Javascript.
let numbers = [1, 3, 1, 5, 4, 3, 5];

numbers = numbers.filter(function (item, index) {
    return numbers.indexOf(item) == index;
});

console.log(numbers)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Output

[1,3,5,4]

Live Demo

Remove duplicates using spread syntax

We all are familiar with the spread syntax in javascript and use it for many processes. We can also use it for removing duplicate elements from the array.

Syntax

[...new Set(array)]

Code Example

const arr = ['b', 'c', 'b', 'd', 'a', 'b', 'c'];

const distinct_arr = [...new Set(arr)];

console.log(distinct_arr);

Output

["b","c","d","a"]

Live Demo

Using For Loop (Fast Performance)

We can also use Javascript For Loop to get the unique array from an array that contains duplicate values. As we know that using functions can cost performance degrade in Javascript so we do that in the old way.

Code Example

const arr = ['b', 'c', 'b', 'd', 'a', 'b', 'c'];

var added = {};
var result = [];
var j = 0;

for (var i = 0; i < arr.length; i++) {
    var item = arr[i];
    if (added[item] !== 1) {
        added[item] = 1;
        result[j++] = item;
    }
}

console.log(result);

Output

["b","c","d","a"]

Live Demo for above code

Was this helpful?
0 Comments