With JavaScript 1.6 / ECMAScript 5 you can use the native filter
method of an Array in the following way to get an array with unique values:(使用JavaScript 1.6 / ECMAScript 5,您可以通过以下方式使用Array的本机filter
方法来获取具有唯一值的数组:)
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']
The native method filter
will loop through the array and leave only those entries that pass the given callback function onlyUnique
.(本地方法filter
将遍历数组,仅保留那些通过给定回调函数onlyUnique
。)
onlyUnique
checks, if the given value is the first occurring.(onlyUnique
检查给定值是否是第一个出现。) If not, it must be a duplicate and will not be copied.(如果不是,它必须是重复的,并且不会被复制。)
This solution works without any extra library like jQuery or prototype.js.(此解决方案无需任何额外的库(如jQuery或prototype.js)即可工作。)
It works for arrays with mixed value types too.(它也适用于具有混合值类型的数组。)
For old Browsers (<ie9), that do not support the native methods filter
and indexOf
you can find work arounds in the MDN documentation for filter and indexOf .(对于旧的浏览器(<IE9),不支持原生的方法filter
和indexOf
你可以找到MDN文档中的变通过滤器和的indexOf 。)
If you want to keep the last occurrence of a value, simple replace indexOf
by lastIndexOf
.(如果要保留最后一次出现的值,只需将indexOf
替换为lastIndexOf
。)
With ES6 it could be shorten to this:(使用ES6可以简化为:)
// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i);
// unique is ['a', 1, 2, '1']
Thanks to Camilo Martin for hint in comment.(感谢Camilo Martin的评论提示。)
ES6 has a native object Set
to store unique values.(ES6有一个本机对象Set
用于存储唯一值。) To get an array with unique values you could do now this:(要获得具有唯一值的数组,您现在可以执行以下操作:)
var myArray = ['a', 1, 'a', 2, '1'];
let unique = [...new Set(myArray)];
// unique is ['a', 1, 2, '1']
The constructor of Set
takes an iterable object, like Array, and the spread operator ...
transform the set back into an Array.(Set
的构造函数采用一个可迭代的对象(例如Array),并且散布运算符...
将集合转换回Array。) Thanks to Lukas Liese for hint in comment.(感谢Lukas Liese的评论提示。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…