如何在数组中获得唯一值的列表?我总是必须使用第二个数组,或者在JavaScript中有类似于java的hashmap的东西吗?
我将只使用JavaScript和jQuery。不能使用其他库。
如何在数组中获得唯一值的列表?我总是必须使用第二个数组,或者在JavaScript中有类似于java的hashmap的东西吗?
我将只使用JavaScript和jQuery。不能使用其他库。
当前回答
我在纯JS中尝试过这个问题。 我遵循了以下步骤1。对给定数组进行排序,2。遍历排序数组,3。用当前值验证前一个值和下一个值
// JS
var inpArr = [1, 5, 5, 4, 3, 3, 2, 2, 2,2, 100, 100, -1];
//sort the given array
inpArr.sort(function(a, b){
return a-b;
});
var finalArr = [];
//loop through the inpArr
for(var i=0; i<inpArr.length; i++){
//check previous and next value
if(inpArr[i-1]!=inpArr[i] && inpArr[i] != inpArr[i+1]){
finalArr.push(inpArr[i]);
}
}
console.log(finalArr);
Demo
其他回答
如果您不需要太担心旧的浏览器,这正是set的设计目的。
Set对象允许您存储任何类型的惟一值 原语值或对象引用。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
const set1 = new Set([1, 2, 3, 4, 5, 1]);
// returns Set(5) {1, 2, 3, 4, 5}
既然我在@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
你只需要香草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
使用第二阵列的短而甜的解决方案;
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
再想想这个问题。下面是我用更少的代码实现这一目标的方法。
var distinctMap = {}; var testArray = ['John', 'John', 'Jason', 'Jason']; For (var I = 0;i < testArray.length;我+ +){ var值= testArray[i]; distinctMap[value] = "; }; var unique_values = Object.keys(distinctMap); console.log (unique_values);