Javascript 如何获取数组中的唯一值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11246758/
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-24 05:07:00  来源:igfitidea点击:

How to get unique values in an array

javascriptjquery

提问by Astronaut

How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java's hashmap in JavaScript?

如何获取数组中唯一值的列表?我是否总是必须使用第二个数组,或者是否有类似于 JavaScript 中 java 的 hashmap 的东西?

I am going to be using JavaScriptand jQueryonly. No additional libraries can be used.

我将只使用JavaScriptjQuery。不能使用额外的库。

采纳答案by Hymanwanders

Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, containsand unique

由于我在@Rocket 的回答的评论中继续讨论它,我不妨提供一个不使用库的示例。这需要两个新的原型函数,contains以及unique

Array.prototype.contains = function(v) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === v) return true;
  }
  return false;
};

Array.prototype.unique = function() {
  var arr = [];
  for (var i = 0; i < this.length; i++) {
    if (!arr.contains(this[i])) {
      arr.push(this[i]);
    }
  }
  return arr;
}

var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]

console.log(uniques);

For more reliability, you can replace containswith MDN's indexOfshim and check if each element's indexOfis equal to -1: documentation

为了获得更高的可靠性,您可以contains用 MDN 的indexOfshim替换并检查每个元素indexOf是否等于 -1:文档

回答by Josh Mc

Or for those looking for a one-liner (simple and functional), compatible with current browsers:

或者对于那些正在寻找与当前浏览器兼容的单线(简单且实用)的人:

let a = ["1", "1", "2", "3", "3", "1"];
let unique = a.filter((item, i, ar) => ar.indexOf(item) === i);
console.log(unique);

Update 18-04-2017

更新 18-04-2017

It appears as though 'Array.prototype.includes' now has widespread support in the latest versions of the mainline browsers (compatibility)

似乎“Array.prototype.includes”现在在最新版本的主线浏览器中得到了广泛的支持(兼容性

Update 29-07-2015:

2015 年 7 月 29 日更新:

There are plans in the works for browsers to support a standardized 'Array.prototype.includes' method, which although does not directly answer this question; is often related.

有计划让浏览器支持标准化的“Array.prototype.includes”方法,虽然它没有直接回答这个问题;往往是相关的。

Usage:

用法:

["1", "1", "2", "3", "3", "1"].includes("2");     // true

Pollyfill (browser support, source from mozilla):

Pollyfill(浏览器支持来自 mozilla):

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

回答by Charles Clayton

Here's a much cleaner solution for ES6 that I see isn't included here. It uses the Setand the spread operator: ...

这是一个更简洁的 ES6 解决方案,我看到这里没有包含。它使用Set扩展运算符...

var a = [1, 1, 2];

[... new Set(a)]

Which returns [1, 2]

哪个返回 [1, 2]

回答by Vamsi

One Liner, Pure JavaScript

单行,纯 JavaScript

With ES6 syntax

使用 ES6 语法

list = list.filter((x, i, a) => a.indexOf(x) === i)

list = list.filter((x, i, a) => a.indexOf(x) === i)

x --> item in array
i --> index of item
a --> array reference, (in this case "list")

enter image description here

在此处输入图片说明

With ES5 syntax

使用 ES5 语法

list = list.filter(function (x, i, a) { 
    return a.indexOf(x) === i; 
});

Browser Compatibility: IE9+

浏览器兼容性:IE9+

回答by Adeel Imran

Using EcmaScript 2016 you can simply do it like this.

使用 EcmaScript 2016,您可以简单地这样做。

 var arr = ["a", "a", "b"];
 var uniqueArray = Array.from(new Set(arr)); // Unique Array ['a', 'b'];

Sets are always unique, and using Array.from()you can convert a Set to an array. For reference have a look at the documentations.

集合总是唯一的,使用Array.from()您可以将集合转换为数组。作为参考,请查看文档。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects /放

回答by Rohit.007

Now in ES6 we can use the newly introduced ES6 function

现在在 ES6 中我们可以使用新引入的 ES6 函数

let items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2]
let uniqueItems = Array.from(new Set(items))

OR by Array spread syntax on iterables

OR 通过可迭代对象上的数组展开语法

let items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2]; 
let uniqueItems = [...new Set(items)];

It will return the unique result.

它将返回唯一的结果。

[1, 3, 4, 5, 2, 23]

回答by kennebec

If you want to leave the original array intact,

如果你想保持原数组不变,

you need a second array to contain the uniqe elements of the first-

您需要第二个数组来包含第一个数组的唯一元素-

Most browsers have Array.prototype.filter:

大多数浏览器都有Array.prototype.filter

var unique= array1.filter(function(itm, i){
    return array1.indexOf(itm)== i; 
    // returns true for only the first instance of itm
});


//if you need a 'shim':
Array.prototype.filter= Array.prototype.filter || function(fun, scope){
    var T= this, A= [], i= 0, itm, L= T.length;
    if(typeof fun== 'function'){
        while(i<L){
            if(i in T){
                itm= T[i];
                if(fun.call(scope, itm, i, T)) A[A.length]= itm;
            }
            ++i;
        }
    }
    return A;
}
 Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
        if(!i || typeof i!= 'number') i= 0;
        var L= this.length;
        while(i<L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }

回答by Fawntasia

These days, you can use ES6's Set data type to convert your array to a unique Set. Then, if you need to use array methods, you can turn it back into an Array:

现在,您可以使用 ES6 的 Set 数据类型将数组转换为唯一的 Set。然后,如果你需要使用数组方法,你可以把它变回一个数组:

var arr = ["a", "a", "b"];
var uniqueSet = new Set(arr); // {"a", "b"}
var uniqueArr = Array.from(uniqueSet); // ["a", "b"]
//Then continue to use array methods:
uniqueArr.join(", "); // "a, b"

回答by Calvin

Not native in Javascript, but plenty of libraries have this method.

不是 Javascript 原生的,但很多库都有这种方法。

Underscore.js's _.uniq(array)(link) works quite well (source).

Underscore.js _.uniq(array)链接)运行良好(源代码)。

回答by Rocket Hazmat

Using jQuery, here's an Array unique function I made:

使用 jQuery,这是我制作的 Array 独特功能:

Array.prototype.unique = function () {
    var arr = this;
    return $.grep(arr, function (v, i) {
        return $.inArray(v, arr) === i;
    });
}

console.log([1,2,3,1,2,3].unique()); // [1,2,3]