Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - remove duplicates from an array of strings [duplicate]

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

like image 698
void Avatar asked Sep 23 '12 10:09

void


2 Answers

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/

like image 72
Guffa Avatar answered Sep 30 '22 01:09

Guffa


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) );
like image 40
KooiInc Avatar answered Sep 30 '22 03:09

KooiInc