36

Possible Duplicate:
Easiest way to find duplicate values in a JavaScript array
jQuery.unique on an array of strings

I'm trying to get a neighbor list by breadth-first search (to be specific: the indexes of same color neighbor balls in Block'd) my function getWholeList(ballid) return an array like

thelist=["ball_1","ball_13","ball_23","ball_1"]

and of course there are duplicates.

I tried to remove them with jQuery.unique(); but it does not work with strings I guess, so is there any way for this(making the array unique) ?

Thanks for any help..

4
  • look at this: stackoverflow.com/questions/840781/… Commented Sep 23, 2012 at 10:42
  • @kleinohad: Just mark it as a duplicate Commented Sep 23, 2012 at 11:32
  • Thanks for all the answers, I found the required function in this topic Commented Sep 23, 2012 at 12:05
  • 1
    for me $.unique it works: jsfiddle.net/8RNYF Commented Jul 15, 2014 at 11:12

5 Answers 5

79

The jQuery unique method only works on an array of DOM elements.

You can easily make your own uniqe function using the each and inArray methods:

function unique(list) {
  var result = [];
  $.each(list, function(i, e) {
    if ($.inArray(e, result) == -1) result.push(e);
  });
  return result;
}

Demo: http://jsfiddle.net/Guffa/Askwb/

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

1 Comment

using grep is also good: function unique(list) { return $.grep(list, function(n, i) { return list.indexOf(n) == i; }); }
15

As a non jquery solution you could use the Arrays filter method like this:

var thelist=["ball_1","ball_13","ball_23","ball_1"], 
    thelistunique = thelist.filter(
                 function(a){if (!this[a]) {this[a] = 1; return a;}},
                 {}
                );
//=> thelistunique = ["ball_1", "ball_13", "ball_23"]

As extension to Array.prototype (using a shortened filter callback)

Array.prototype.uniq = function(){
  return this.filter(
      function(a){return !this[a] ? this[a] = true : false;}, {}
  );
}
thelistUnique = thelist.uniq(); //=> ["ball_1", "ball_13", "ball_23"]

[Edit 2017] An ES6 take on this could be:

const unique = arr => [...new Set(arr)];
const someArr = ["ball_1","ball_13","ball_23","ball_1", "ball_13", "ball_1" ];
console.log( unique(someArr) );

Comments

9

Try this one - Array.unique()

Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };
thelist=["ball_1","ball_13","ball_23","ball_1"]
thelist=thelist.unique()

2 Comments

don't try this on large arrays though, this has quadratic complexity
doesn't this also sort the array? Sometimes this is unwanted
2

jQuery.unique() only works for array of DOM elements. Take a look at this (enhanced version of unique) :

Enhanced unique

Comments

2

There is a JavaScript port of the PHP array_unique function here: http://phpjs.org/functions/array_unique

function array_unique (inputArr) {
    var key = '',
        tmp_arr2 = {},
        val = '';

    var __array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if (haystack.hasOwnProperty(fkey)) {
                if ((haystack[fkey] + '') === (needle + '')) {
                    return fkey;
                }
            }
        }
        return false;
    };

    for (key in inputArr) {
        if (inputArr.hasOwnProperty(key)) {
            val = inputArr[key];
            if (false === __array_search(val, tmp_arr2)) {
                tmp_arr2[key] = val;
            }
        }
    }

    return tmp_arr2;
}

Or as of later JS:

arr.filter((v, p) => arr.indexOf(v) == p)

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.