如何获取数组中唯一值的列表?我是否总是必须使用第二个数组,或者在JavaScript中是否有类似于java的hashmap的东西?
我将只使用JavaScript和jQuery。不能使用其他库。
发布于 2012-06-28 22:58:50
由于我在@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);
为了获得更高的可靠性,可以用MDN的indexOf填充程序替换contains,并检查每个元素的indexOf是否等于-1:documentation
发布于 2017-02-09 05:30:25
发布于 2014-04-25 08:13:31
或者,对于那些寻找与当前浏览器兼容的一行程序(简单且功能强大)的的人来说
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”方法,尽管它不能直接回答这个问题,但通常是相关的。
用法:
["1", "1", "2", "3", "3", "1"].includes("2"); // truePollyfill (browser support,source from 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;
}
});
}https://stackoverflow.com/questions/11246758
复制相似问题