如何在数组中获取唯一值

Ast*_*aut 145 javascript jquery

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

我将只使用JavaScriptjQuery.不能使用其他库.

Jos*_* Mc 186

或者对于那些寻找单线程(简单和功能),与当前浏览器兼容的人:

let a = ["1", "1", "2", "3", "3", "1"];
let unique = a.filter((item, i, ar) => ar.indexOf(item) === i);
console.log(unique);
Run Code Online (Sandbox Code Playgroud)

更新18-04-17

似乎'Array.prototype.includes'现在在最新版本的主线浏览器中得到广泛支持(兼容性)

2015年7月29日更新:

浏览器的工作计划是支持标准化的'Array.prototype.includes'方法,虽然它没有直接回答这个问题; 通常是相关的.

用法:

["1", "1", "2", "3", "3", "1"].includes("2");     // true
Run Code Online (Sandbox Code Playgroud)

Pollyfill(浏览器支持,来自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;
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 糟糕的答案。O(N^2) 复杂度。不要使用这个。 (2认同)

jac*_*ers 113

自从我在@Rocket答案的评论中继续讨论它以来,我不妨提供一个不使用库的例子.这需要两个新的原型函数,containsunique

Array.prototype.contains = function(v) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === v) return true;
  }
  return false;
};

Array.prototype.unique = function() {
  var arr = [];
  for (var i = 0; i < this.length; i++) {
    if (!arr.contains(this[i])) {
      arr.push(this[i]);
    }
  }
  return arr;
}

var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]

console.log(uniques);
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

Array.prototype.contains = function(v) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === v) return true;
  }
  return false;
};

Array.prototype.unique = function() {
  var arr = [];
  for (var i = 0; i < this.length; i++) {
    if (!arr.contains(this[i])) {
      arr.push(this[i]);
    }
  }
  return arr;
}

var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];
var uniques = duplicates.unique(); // result = [1,3,4,2,8]

console.log(uniques);
Run Code Online (Sandbox Code Playgroud)

为了获得更高的可靠性,您可以contains使用MDN的indexOf垫片替换并检查每个元素indexOf是否等于-1:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

  • 这具有高运行时间复杂度(最坏情况:O(n ^ 2)) (4认同)
  • 这是一个非常低效的实现。检查结果数组以查看它是否已经包含一个项目是可怕的。更好的方法是使用跟踪计数的对象,或者如果您不想使用辅助存储,请先在 O(n log n) 中对其进行排序,然后进行线性扫描并并排比较元素 (4认同)
  • 我们真的需要“包含”功能吗? (2认同)
  • `Array.from(new Set(arr))` *极大地*快:https://jsperf.com/unique-func-vs-set/1 - 公平地说,这可能是一个很好的答案已编写,但您现在“不应该”使用它。 (2认同)

Cha*_*ton 103

这是一个更清洁的ES6解决方案,我看到这里没有包含.它使用Setspread运算符:...

var a = [1, 1, 2];

[... new Set(a)]
Run Code Online (Sandbox Code Playgroud)

哪个回报 [1, 2]

  • 在Typescript中你必须使用`Array.from(... new Set(a))`因为Set不能隐式转换为数组类型.只是一个抬头! (6认同)
  • 现在,**这个**是单线! (5认同)

Vam*_*msi 68

One Liner,Pure JavaScript

使用ES6语法

list = list.filter((x, i, a) => a.indexOf(x) == i)

x --> item in array
i --> index of item
a --> array reference, (in this case "list")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

使用ES5语法

list = list.filter(function (x, i, a) { 
    return a.indexOf(x) == i; 
});
Run Code Online (Sandbox Code Playgroud)

浏览器兼容性:IE9 +

  • 如果你把所有东西放在一条线上,一切都是一线的:-) (5认同)
  • 不知道为什么会被投票.一开始它可能有点模糊,而且_perhaps_被归类为"聪明"而不是实用的阅读,但它是陈述性的,非破坏性的,简洁的,其中大多数其他答案都缺乏. (4认同)
  • @Larry 这被否决了,因为在此之前几年提供了完全相同的答案。 (2认同)

Ade*_*ran 17

使用EcmaScript 2016,你可以这样做.

 var arr = ["a", "a", "b"];
 var uniqueArray = Array.from(new Set(arr)); // Unique Array ['a', 'b'];
Run Code Online (Sandbox Code Playgroud)

集始终是唯一的,使用Array.from()您可以将Set转换为数组.有关参考,请查看文档.

来自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects /组

  • 这是您应该使用的答案。`indexOf()` 的答案很糟糕,因为它们是 O(N^2)。分散的答案是好的,但不适用于大型数组。这是最好的方法。 (2认同)

ken*_*bec 16

如果要保留原始数组,

你需要第二个数组来包含第一个的uniqe元素 -

大多数浏览器有Array.prototype.filter:

var unique= array1.filter(function(itm, i){
    return array1.indexOf(itm)== i; 
    // returns true for only the first instance of itm
});


//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;
    }
Run Code Online (Sandbox Code Playgroud)


Roh*_*007 15

现在在ES6中我们可以使用新引入的ES6功能

var items = [1,1,1,1,3,4,5,2,23,1,4,4,4,2,2,2]
var uniqueItems = Array.from(new Set(items))
Run Code Online (Sandbox Code Playgroud)

它将返回唯一的结果.

[1, 3, 4, 5, 2, 23]
Run Code Online (Sandbox Code Playgroud)


小智 12

现在,您可以使用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"
Run Code Online (Sandbox Code Playgroud)

  • 如果您正在使用转译器或在支持它的环境中,您可以更简洁地做同样的事情:`var uniqueArr = [...new Set(arr)]; // ["a", "b"]` (3认同)

Pau*_*per 8

如果您不需要太担心旧版浏览器,这正是 Sets 的设计目的。

\n\n
\n

Set 对象允许您存储任何类型的唯一值,无论是原始值还是对象引用。

\n
\n\n

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

\n\n
const set1 = new Set([1, 2, 3, 4, 5, 1]);\n// returns Set(5)\xc2\xa0{1, 2, 3, 4, 5}\n
Run Code Online (Sandbox Code Playgroud)\n


Cal*_*vin 7

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

Underscore.js _.uniq(array)(链接)工作得很好(来源).


use*_*323 7

快速、紧凑、无嵌套循环,适用于任何对象而不仅仅是字符串和数字,需要一个谓词,并且只有 5 行代码!!

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

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

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'}
//  ] 
Run Code Online (Sandbox Code Playgroud)

如果您希望它找到第一个唯一项目而不是最后一个,请在其中添加 found.hasOwnPropery() 检查。


Roc*_*mat 6

使用jQuery,这是我做的一个Array独特的函数:

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]
Run Code Online (Sandbox Code Playgroud)

  • 如果你要在核心javascript对象的原型中使用jQuery,写一个jQuery函数可能不是更好,比如`$ .uniqueArray(arr)`?在`Array`的原型中嵌入对jQuery的引用似乎有问题 (5认同)
  • @jackwanders:这有什么值得怀疑的?如果页面上有 jQuery,我们就使用它。 (2认同)
  • 这是我的观点; 如果你打算使用jQuery,那么让函数本身成为jQuery的一部分.如果我要扩展核心对象的原型,我会坚持核心javascript,只是为了让事情可以重用.如果其他人正在查看您的代码,很明显`$ .uniqueArray`依赖于jQuery; 不太明显的是`Array.prototype.unique`也是如此. (2认同)

Pra*_*kar 6

使用第二阵列的短而甜的解决方案;

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
Run Code Online (Sandbox Code Playgroud)


Rah*_*ora 5

上述大多数解决方案都具有很高的运行时间复杂度。

这是使用reduce并且可以在O(n) 时间内完成工作的解决方案

Array.prototype.unique = Array.prototype.unique || function() {
        var arr = [];
	this.reduce(function (hash, num) {
		if(typeof hash[num] === 'undefined') {
			hash[num] = 1; 
			arr.push(num);
		}
		return hash;
	}, {});
	return arr;
}
    
var myArr = [3,1,2,3,3,3];
console.log(myArr.unique()); //[3,1,2];
Run Code Online (Sandbox Code Playgroud)

笔记:

此解决方案不依赖于 reduce。这个想法是创建一个对象映射并将唯一的映射到数组中。


归档时间:

查看次数:

247171 次

最近记录:

6 年 前