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

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


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:

Array.from(["ball_1","ball_13","ball_23","ball_1"]           .reduce( (a, b) => a.set(b, b) , new Map()))     .map( v => v[1] );


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()