首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何获取数组中的唯一值

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

Stack Overflow用户
提问于 2012-06-28 22:22:05
回答 20查看 404.7K关注 0票数 228

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

我将只使用JavaScriptjQuery。不能使用其他库。

EN

回答 20

Stack Overflow用户

回答已采纳

发布于 2012-06-28 22:58:50

由于我在@Rocket的答案的评论中继续讨论了这一点,我不妨提供一个不使用库的示例。这需要两个新的原型函数containsunique

代码语言:javascript
运行
复制
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);

为了获得更高的可靠性,可以用MDN的indexOf填充程序替换contains,并检查每个元素的indexOf是否等于-1:documentation

票数 134
EN

Stack Overflow用户

发布于 2017-02-09 05:30:25

这里有一个更干净的ES6解决方案,我认为这里没有包含它。它使用Setspread operator...

代码语言:javascript
运行
复制
var a = [1, 1, 2];

[... new Set(a)]

它返回[1, 2]

票数 274
EN

Stack Overflow用户

发布于 2014-04-25 08:13:31

或者,对于那些寻找与当前浏览器兼容的一行程序(简单且功能强大)的的人来说

代码语言:javascript
运行
复制
let a = ["1", "1", "2", "3", "3", "1"];
let unique = a.filter((item, i, ar) => ar.indexOf(item) === i);
console.log(unique);

更新2021我建议查看Charles Clayton's answer below,因为最近对JS的更改有更简洁的方法可以做到这一点。

更新18-04-2017

似乎'Array.prototype.includes‘现在在最新版本的主流浏览器(compatibility)中得到了广泛的支持。

更新29-07-2015:

有计划让浏览器支持标准化的“Array.prototype.includes”方法,尽管它不能直接回答这个问题,但通常是相关的。

用法:

代码语言:javascript
运行
复制
["1", "1", "2", "3", "3", "1"].includes("2");     // true

Pollyfill (browser supportsource from mozilla):

代码语言:javascript
运行
复制
// 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;
    }
  });
}
票数 272
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11246758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档