如何在数组中获得唯一值的列表?我总是必须使用第二个数组,或者在JavaScript中有类似于java的hashmap的东西吗?

我将只使用JavaScript和jQuery。不能使用其他库。


当前回答

你只需要香草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

其他回答

现在,您可以使用ES6的Set数据类型将数组转换为唯一的Set。然后,如果你需要使用数组方法,你可以把它变回数组:

var arr = ["a", "a", "b"];
var uniqueSet = new Set(arr); // {"a", "b"}
var uniqueArr = Array.from(uniqueSet); // ["a", "b"]
//Then continue to use array methods:
uniqueArr.join(", "); // "a, b"

既然我在@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

你可以输入带有重复元素的数组,下面的方法将返回带有唯一元素的数组。

function getUniqueArray(array){
    var uniqueArray = [];
    if (array.length > 0) {
       uniqueArray[0] = array[0];
    }
    for(var i = 0; i < array.length; i++){
        var isExist = false;
        for(var j = 0; j < uniqueArray.length; j++){
            if(array[i] == uniqueArray[j]){
                isExist = true;
                break;
            }
            else{
                isExist = false;
            }
        }
        if(isExist == false){
            uniqueArray[uniqueArray.length] = array[i];
        }
    }
    return uniqueArray;
}

上面的大多数解决方案都具有较高的运行时复杂性。

下面是使用reduce的解决方案,可以在O(n)时间内完成工作。

Array.prototype.unique = Array.prototype.unique || function() { Var arr = []; 这一点。Reduce(函数(哈希,num) { If (typeof hash[num] === 'undefined') { Hash [num] = 1; arr.push (num); } 返回哈希; }, {}); 返回arr; } var myArr = [3,1,2,3,3,3]; console.log (myArr.unique ());/ /(3、1、2);

注意:

这个解决方案不依赖于reduce。其思想是创建一个对象映射,并将唯一的对象推入数组。

快速,紧凑,无嵌套循环,适用于任何对象,不只是字符串和数字,接受谓词,只有5行代码!!

function findUnique(arr, predicate) {
  var found = {};
  arr.forEach(d => {
    found[predicate(d)] = d;
  });
  return Object.keys(found).map(key => found[key]); 
}

示例:按类型查找唯一项:

var things = [
  { name: 'charm', type: 'quark'},
  { name: 'strange', type: 'quark'},
  { name: 'proton', type: 'boson'},
];

var result = findUnique(things, d => d.type);
//  [
//    { name: 'charm', type: 'quark'},
//    { name: 'proton', type: 'boson'}
//  ] 

如果你想让它找到第一个唯一的项目,而不是最后一个,在那里添加一个find . hasownproperty()检查。