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?

2
  • By "not have the same elements", do you mean you want to check if there are no duplicates? Commented Nov 11, 2013 at 8:08
  • but this has same elements. Try to define your question bit more. Commented Nov 11, 2013 at 8:12

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

If it helped you please accept it as answered or vote it up plz.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.