[Solved-5 Solutions] Remove duplicate from javascript array - javascript Tutorial



Problem:

How to remove duplicate values from JavaScript array ?

Solution 1:

Using jQuery:

var names = ["Mark Twain", "John Steinbeck", "William Faulkner", "William Faulkner", "Robert Frost", "Walt Whitman", "William Faulkner"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});

Solution 2:

Use this code.

let names = ['Mark Twain', 'John Steinbeck', 'William Faulkner', 'William Faulkner', 'Robert Frost', 'Walt Whitman', 'William Faulkner'];
let dup = [...new Set(names)];
console.log(dup);

Solution 3:

This code using an array filter and indexOf functions:

arr = arr.filter (function (value, index, array) { 
    return array.indexOf (value) == index;
});

Solution 4:

function removeDuplicateUsingFilter(arr){
    let unique_array = arr.filter(function(elem, index, self) {
        return index == self.indexOf(elem);
    });
    return unique_array
}
console.log(removeDuplicateUsingFilter(array_with_duplicates));

Solution 5:

UniqueArray contains no duplicates.

var Array = duplicateArray.filter(function(elem, pos) {
    return duplicateArray.indexOf(elem) == pos;
});


Related Searches to Remove duplicate from javascript array - javascript tutorial