Alex Rivera | Logout

How do I make an array with unique elements (i.e. remove duplicates)?

Asked 2011-08-04T10:53:03.017
32

I have this code:

var ar = [10,7,8,3,4,7,6];

function isin(n,a){
  for (var i=0;i<a.length;i++){
    if (a[i]== n) {
      var b = true;
      return b;
    } else {
      var c = false;
      return c;
   }
  }
}

function unique(a){
  var arr = [];
  for (var i=0;i<a.length;i++){
    if (!isin(a[i],arr)){
      arr.push(a[i]);
    }
  }

 return arr;
}

alert(unique(ar));

In this code, I try to create new unique array (without duplicates) out of the original one. But I still get the original array! Where's my mistake?

Edit
Report

3 Answers

6

Edit: note the warning by Daniel. Considering that, and what the official docs say (below), maybe using this is not a great idea after all!


If you happen to use jQuery, its unique() function does this:

var ar = [1, 2, 1, 2, 2, 3];    
ar = $.unique(ar);
console.log(ar);  // [3, 2, 1] 

The documentation says:

Note that this only works on arrays of DOM elements, not strings or numbers.

...but when I tested this with jQuery 1.9.1, it does work for strings and numbers too. Anyway, double-check that it works, especially if using older jQuery.

answered 2013-05-08T09:07:29.340
3

Because your isin method returns true or false after examining the first element.

change it to this:

function isin(n,a){
  for (var i=0;i<a.length;i++){
    if (a[i]== n){
    return true;

    }
  }
  return false;
}
answered 2011-08-04T10:57:10.417
2

You should use indexOf instead of your isIn function:

function unique(a){
  var arr = [];
  for (var i=0;i<a.length;i++){
    if ( arr.indexOf(a[i]) == -1){
        arr.push(a[i]);
    }
}
answered 2011-08-04T10:57:03.563

Your Answer