如何获取数组中的唯一值 [英] How to get unique values in an array

查看:30
本文介绍了如何获取数组中的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

我将仅使用 JavaScriptjQuery.不能使用额外的库.

I am going to be using JavaScript and jQuery only. No additional libraries can be used.

推荐答案

既然我在@Rocket 的答案的评论中继续讨论它,我也可以提供一个不使用库的示例.这需要两个新的原型函数,containsunique

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, contains and 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);

为了更可靠,你可以用 MDN 的 indexOf shim 替换 contains 并检查每个元素的 indexOf 是否等于 -1:文档

For more reliability, you can replace contains with MDN's indexOf shim and check if each element's indexOf is equal to -1: documentation

这篇关于如何获取数组中的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆