如何在数组中获得唯一值的列表?我总是必须使用第二个数组,或者在JavaScript中有类似于java的hashmap的东西吗?
我将只使用JavaScript和jQuery。不能使用其他库。
如何在数组中获得唯一值的列表?我总是必须使用第二个数组,或者在JavaScript中有类似于java的hashmap的东西吗?
我将只使用JavaScript和jQuery。不能使用其他库。
当前回答
使用EcmaScript 2016,你可以简单地像这样做。
var arr = ["a", "a", "b"];
var uniqueArray = Array.from(new Set(arr)); // Unique Array ['a', 'b'];
集合总是唯一的,使用array. from()可以将集合转换为数组。参考一下文件。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
其他回答
既然我在@Rocket的回答的评论中谈到了它,我不妨提供一个不使用库的示例。这需要两个新的原型功能,包含和唯一
Array.prototype.contains =函数(v) { For (var I = 0;I < this.length;我+ +){ If (this[i] === v)返回true; } 返回错误; }; Array.prototype.unique = function() { Var arr = []; For (var I = 0;I < this.length;我+ +){ If (!arr.contains(this[i])) { arr.push(这[我]); } } 返回arr; } Var duplicate = [1,3,4,2,1,2,3,8]; Var uniques = duplicate .unique();// result = [1,3,4,2,8] console.log(独立);
为了获得更高的可靠性,您可以用MDN的indexOf shim替换contains,并检查每个元素的indexOf是否等于-1:documentation
如果你想保持原始数组不变,
您需要第二个数组来包含第一个-的唯一元素
大多数浏览器都有Array.prototype.filter:
const unique = array1.filter((item, index, array) => array.indexOf(item) === index);
//if you need a 'shim':
Array.prototype.filter= Array.prototype.filter || function(fun, scope){
var T= this, A= [], i= 0, itm, L= T.length;
if(typeof fun== 'function'){
while(i<L){
if(i in T){
itm= T[i];
if(fun.call(scope, itm, i, T)) A[A.length]= itm;
}
++i;
}
}
return A;
}
Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
if(!i || typeof i!= 'number') i= 0;
var L= this.length;
while(i<L){
if(this[i]=== what) return i;
++i;
}
return -1;
}
使用jQuery,这是一个数组唯一的函数我做:
Array.prototype.unique = function () {
var arr = this;
return $.grep(arr, function (v, i) {
return $.inArray(v, arr) === i;
});
}
console.log([1,2,3,1,2,3].unique()); // [1,2,3]
使用第二阵列的短而甜的解决方案;
var axes2=[1,4,5,2,3,1,2,3,4,5,1,3,4];
var distinct_axes2=[];
for(var i=0;i<axes2.length;i++)
{
var str=axes2[i];
if(distinct_axes2.indexOf(str)==-1)
{
distinct_axes2.push(str);
}
}
console.log("distinct_axes2 : "+distinct_axes2); // distinct_axes2 : 1,4,5,2,3
你只需要香草JS找到唯一的数组。some和Array.reduce。在ES2015语法中,它只有62个字符。
a.reduce((c, v) => b.some(w => w === v) ? c : c.concat(v)), b)
数组中。some和Array。IE9+和其他浏览器支持。只需要在不支持ES2015语法的浏览器中修改常规函数的胖箭头函数即可。
var a = [1,2,3];
var b = [4,5,6];
// .reduce can return a subset or superset
var uniques = a.reduce(function(c, v){
// .some stops on the first time the function returns true
return (b.some(function(w){ return w === v; }) ?
// if there's a match, return the array "c"
c :
// if there's no match, then add to the end and return the entire array
c.concat(v)}),
// the second param in .reduce is the starting variable. This is will be "c" the first time it runs.
b);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce