Javascript jQuery - 从字符串数组中删除重复项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12551635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:40:59  来源:igfitidea点击:

jQuery - remove duplicates from an array of strings

javascriptjqueryarraysstringunique

提问by void

Possible Duplicate:
Easiest way to find duplicate values in a JavaScript array
jQuery.unique on an array of strings

可能的重复:
字符串数组上的JavaScript 数组jQuery.unique 中查找重复值的最简单方法

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

我正在尝试通过广度优先搜索来获取邻居列表(具体来说:Block'd中相同颜色邻居球的索引)我function getWholeList(ballid)返回一个数组

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

我试图用 jQuery.unique(); 删除它们。但我猜它不适用于字符串,所以有什么方法可以做到这一点(使数组唯一)?

Thanks for any help..

谢谢你的帮助..

回答by Guffa

The jQuery uniquemethodonly works on an array of DOM elements.

jQueryunique方法仅适用于 DOM 元素数组。

You can easily make your own uniqe function using the eachand inArraymethods:

您可以使用eachinArray方法轻松创建自己的 uniqe 函数:

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/

演示:http: //jsfiddle.net/Guffa/Askwb/

回答by KooiInc

As a non jquery solution you could use the Arrays filtermethod like this:

作为非 jquery 解决方案,您可以filter像这样使用 Arrays方法:

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

作为扩展Array.prototype(使用缩短的filter回调)

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:

[ Edit 2017] ES6 对此的看法可能是:

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

回答by white

Try this one - Array.unique()

试试这个 - 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()

回答by obe6

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

jQuery.unique() 仅适用于 DOM 元素数组。看看这个(unique的增强版):

Enhanced unique

增强型独特

回答by Petah

There is a JavaScript port of the PHP array_uniquefunction here: http://phpjs.org/functions/array_unique

这里有 PHParray_unique函数的 JavaScript 端口: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:

或者从后来的 JS 开始:

arr.filter((v, p) => arr.indexOf(v) == p)