1

I have an array

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

How to check, that this array does not have the same elements?

Sarath
  • 9,030
  • 11
  • 51
  • 84
toshkaexe
  • 67
  • 1
  • 9

3 Answers3

0

Try this,

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

Demos with duplicate and unique elements

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

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);
Ricky Stam
  • 2,116
  • 21
  • 25
0

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

prograhammer
  • 20,132
  • 13
  • 91
  • 118