如何在数组中获取唯一值 [英] How to get unique values in an array
问题描述
如何获取数组中唯一值的列表?我是否总是必须使用第二个数组,或者在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答案的评论中继续讨论它,我也可以提供一个不使用库的示例。这需要两个新的原型函数,包含
和唯一
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.includes(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]
为了获得更高的可靠性,你可以用MDN的 indexOf
shim替换包含
并检查每个元素的 indexOf
等于-1: https://developer.mozilla.org/ en / JavaScript / Reference / Global_Objects / Array / indexOf
For more reliability, you can replace contains
with MDN's indexOf
shim and check if each element's indexOf
is equal to -1: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
这篇关于如何在数组中获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!