jQuery - remove duplicates from an array of string

2020-02-17 10:25发布

问题:

This question already has answers here:
Closed 7 years ago.

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

回答1:

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/



回答2:

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] );


回答3:

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


回答4:

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

Enhanced unique



回答5:

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)