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

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


当前回答

再想想这个问题。下面是我用更少的代码实现这一目标的方法。

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);

其他回答

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

或者对于那些寻找与当前浏览器兼容的一行程序(简单而实用)的人:

Let a = ["1", "1", "2", "3", "3", "1"]; let unique = a.filter((item, i, ar) => ar. indexof (item) === i); console.log(独特的);

更新2021 我建议你去看看Charles Clayton的答案,在JS的最新修改中,甚至有更简洁的方法来做到这一点。

更新18-04-2017

它看起来就像'Array.prototype。Includes '现在在主流浏览器的最新版本中得到了广泛支持(兼容性)

更新29-07-2015:

目前正在计划让浏览器支持标准化的“Array.prototype”。方法,虽然没有直接回答这个问题;往往是相关的。

用法:

["1", "1", "2", "3", "3", "1"].includes("2");     // true

polyfill(浏览器支持,来自mozilla):

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

如果你想保持原始数组不变,

您需要第二个数组来包含第一个-的唯一元素

大多数浏览器都有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;
    }

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