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

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


当前回答

在Javascript中不是原生的,但是很多库都有这个方法。

Underscore.js的_.uniq(array) (link)工作得很好(来源)。

其他回答

快速,紧凑,无嵌套循环,适用于任何对象,不只是字符串和数字,接受谓词,只有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()检查。

我在想我们能不能用线性搜索来消除重复项

JavaScript:
function getUniqueRadios() {

var x=document.getElementById("QnA");
var ansArray = new Array();
var prev;


for (var i=0;i<x.length;i++)
  {
    // Check for unique radio button group
    if (x.elements[i].type == "radio")
    {
            // For the first element prev will be null, hence push it into array and set the prev var.
            if (prev == null)
            {
                prev = x.elements[i].name;
                ansArray.push(x.elements[i].name);
            } else {
                   // We will only push the next radio element if its not identical to previous.
                   if (prev != x.elements[i].name)
                   {
                       prev = x.elements[i].name;
                       ansArray.push(x.elements[i].name);
                   }
            }
    }

  }

   alert(ansArray);

}

HTML:

<body>

<form name="QnA" action="" method='post' ">

<input type="radio"  name="g1" value="ANSTYPE1"> good </input>
<input type="radio" name="g1" value="ANSTYPE2"> avg </input>

<input type="radio"  name="g2" value="ANSTYPE3"> Type1 </input>
<input type="radio" name="g2" value="ANSTYPE2"> Type2 </input>


<input type="submit" value='SUBMIT' onClick="javascript:getUniqueRadios()"></input>


</form>
</body>
Array.prototype.unique = function () {
    var dictionary = {};
    var uniqueValues = [];
    for (var i = 0; i < this.length; i++) {
        if (dictionary[this[i]] == undefined){
            dictionary[this[i]] = i;
            uniqueValues.push(this[i]);
        }
    }
    return uniqueValues; 
}

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

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

下面是使用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。其思想是创建一个对象映射,并将唯一的对象推入数组。