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..
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/
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) );  If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With