如何获取数组中的唯一值
如何获取数组中唯一值的列表?我是否总是必须使用第二个数组,或者是否有类似于 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?
我将仅使用 JavaScript 和 jQuery.不能使用额外的库.
I am going to be using JavaScript and jQuery only. No additional libraries can be used.
既然我在@Rocket 的答案的评论中继续讨论它,我也可以提供一个不使用库的示例.这需要两个新的原型函数,contains
和 unique
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