filter array for duplicates javascript code example

Example 1: javascript to remove duplicates from an array

uniqueArray = a.filter(function(item, pos) {
    return a.indexOf(item) == pos; 
})

Example 2: javascript filter array remove duplicates

// Using the Set constructor and the spread syntax:

arrayWithOnlyUniques = [...new Set(arrayWithDuplicates)]

Example 3: javascript remove duplicates from array

unique = [...new Set(arr)];   // where arr contains duplicate elements

Example 4: javascript remove duplicates from array

function toUniqueArray(a){
    var newArr = [];
    for (var i = 0; i < a.length; i++) {
        if (newArr.indexOf(a[i]) === -1) {
            newArr.push(a[i]);
        }
    }
  return newArr;
}
var colors = ["red","red","green","green","green"];
var colorsUnique=toUniqueArray(colors); // ["red","green"]

Tags:

Php Example