jQuery - remove duplicates from an array of strings

void picture void · Sep 23, 2012 · Viewed 96.7k times · Source

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..

Answer

Guffa picture Guffa · Sep 23, 2012

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/