Skip to content Skip to sidebar Skip to footer

I Need To Check A Javascript Array To See If There Are Any Duplicate Values.

I have an array var a =['color', 'radius', 'y', 'x', 'x', 'x']; How to check, that this array does not have the same elements?

Solution 1:

Try this,

var a = ["color", "radius", "y", "x", "x", "x"];
var uniqueval = a.filter(function (itm, i, a) {// array of unique elementsreturn i == a.indexOf(itm);
});
if (a.length > uniqueval.length) {
    alert("duplicate elements")
}
else{
    alert('Unique elements')
}

Demos with duplicate and unique elements

Solution 2:

If the newArray has elements inside it then you have dublicates. You can then remove the elements of newArray from the original Array.

var a = ["color", "radius", "y", "x", "x", "x"];
var sortA = a.sort();
var newArray = [];
for (var i = 0; i < a.length - 1; i++) {
    if (sortA[i + 1] == sortA[i]) {
        newArray.push(sortA[i]);
    }
}

alert(newArray);

Solution 3:

This is super simple:

var i, a = ["color", "radius", "y", "x", "x", "x"];

for (i = 0; i < a.length; ++i) {
    if(a.indexOf(a[i]) != a.lastIndexOf(a[i]))
          alert("Duplicate found!");
}

Fiddle here

Post a Comment for "I Need To Check A Javascript Array To See If There Are Any Duplicate Values."