获取数组中的所有惟一值(删除重复值)

时间:2021-10-22 11:41:02

I have an array of numbers that I need to make sure are unique. I found the code snippet below on the internet and it works great until the array has a zero in it. I found this other script here on SO that looks almost exactly like it, but it doesn't fail.

我有一个数组,我需要确保它是唯一的。我在internet上找到了下面的代码片段,它非常好用,直到数组中有一个0。我在这里找到了另一个脚本,看起来几乎和它一样,但是它不会失败。

So for the sake of helping me learn, can someone help me determine where the prototype script is going wrong?

为了帮助我学习,有人能帮我确定原型脚本哪里出错了吗?

Array.prototype.getUnique = function() {
 var o = {}, a = [], i, e;
 for (i = 0; e = this[i]; i++) {o[e] = 1};
 for (e in o) {a.push (e)};
 return a;
}

More answers from duplicate question:

Similar question:

59 个解决方案

#1


1401  

With JavaScript 1.6 / ECMAScript 5 you can use the native filter method of an Array in the following way to get an array with unique values:

使用JavaScript 1.6 / ECMAScript 5,您可以使用数组的本机筛选方法来获取具有惟一值的数组:

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']

The native method filter will loop through the array and leave only those entries that pass the given callback function onlyUnique.

本机方法过滤器将循环遍历数组,只保留传递给定回调函数的条目only unique。

onlyUnique checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied.

只有在给定值是第一次出现时才进行唯一检查。如果没有,它必须是一个副本,并且不会被复制。

This solution works without any extra library like jQuery or prototype.js.

这个解决方案不需要任何额外的库,比如jQuery或prototype.js。

It works for arrays with mixed value types too.

它也适用于具有混合值类型的数组。

For old Browsers (<ie9), that do not support the native methods filter and indexOf you can find work arounds in the MDN documentation for filter and indexOf.

对于旧的浏览器( ),不支持本机方法过滤器和indexof的浏览器可以在mdn文档中找到过滤器和indexof的工作。

If you want to keep the last occurrence of a value, simple replace indexOf by lastIndexOf.

如果希望保留值的最后出现,可以使用lastIndexOf简单替换indexOf。

With ES6 it could be shorten to this:

有了ES6,它可以缩短为:

// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i); 

// unique is ['a', 1, 2, '1']

Thanks to Camilo Martin for hint in comment.

感谢卡米洛·马丁的评论暗示。

ES6 has a native object Set to store unique values. To get an array with unique values you could do now this:

ES6有一个本机对象集来存储惟一值。要获得一个具有独特值的数组,您可以这样做:

var myArray = ['a', 1, 'a', 2, '1'];

let unique = [...new Set(myArray)]; 

// unique is ['a', 1, 2, '1']

The constructor of Set takes an iterable object, like Array, and the spread operator ... transform the set back into an Array. Thanks to Lukas Liese for hint in comment.

Set的构造函数接受一个可迭代的对象,如Array和spread操作符…将这个集合转换为一个数组。感谢Lukas Liese的建议。

#2


451  

Updated answer for ES6/ES2015: Using the Set, the single line solution is:

ES6/ES2015的更新答案:使用Set,单线解决方案是:

var items = [4,5,4,6,3,4,5,2,23,1,4,4,4]
var uniqueItems = Array.from(new Set(items))

Which returns

它返回

[4, 5, 6, 3, 2, 23, 1]

As le_m suggested, this can also be shortened using spread operator , like

正如le_m所建议的,这也可以通过使用扩展运算符(例如)来缩短

var uniqueItems = [...new Set(items)]

#3


115  

You can also use underscore.js.

您还可以使用underscore.js。

console.log(_.uniq([1, 2, 1, 3, 1, 4]));
<script src="http://underscorejs.org/underscore-min.js"></script>

which will return:

这将返回:

[1, 2, 3, 4]

#4


85  

I realise this question has more than 30 answers already. But I've read through all the existing answers first and made my own research.

我知道这个问题已经有30多个答案了。但我先通读了所有现有的答案,并做了自己的研究。

I split all answers to 4 possible solutions:

我把所有的答案分成四种:

  1. Use new ES6 feature: [...new Set( [1, 1, 2] )];
  2. 使用新的ES6功能:[…新集合([1,1,2])];
  3. Use object { } to prevent duplicates
  4. 使用对象{}来防止重复。
  5. Use helper array [ ]
  6. 使用辅助数组[]
  7. Use filter + indexOf
  8. 使用过滤器+ indexOf

Here's sample codes found in answers:

以下是在答案中找到的示例代码:

Use new ES6 feature: [...new Set( [1, 1, 2] )];

function uniqueArray0(array) {
  var result = Array.from(new Set(array));
  return result    
}

Use object { } to prevent duplicates

function uniqueArray1( ar ) {
  var j = {};

  ar.forEach( function(v) {
    j[v+ '::' + typeof v] = v;
  });

  return Object.keys(j).map(function(v){
    return j[v];
  });
} 

Use helper array [ ]

function uniqueArray2(arr) {
    var a = [];
    for (var i=0, l=arr.length; i<l; i++)
        if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
            a.push(arr[i]);
    return a;
}

Use filter + indexOf

function uniqueArray3(a) {
  function onlyUnique(value, index, self) { 
      return self.indexOf(value) === index;
  }

  // usage
  var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']

  return unique;
}

And I wondered which one is faster. I've made sample Google Sheet to test functions. Note: ECMA 6 is not avaliable in Google Sheets, so I can't test it.

我想知道哪个更快。我做了谷歌样本表来测试函数。注意:ECMA 6在谷歌版中是不可用的,所以我不能测试它。

Here's the result of tests: 获取数组中的所有惟一值(删除重复值)

以下是测试结果:

I expected to see that code using object { } will win because it uses hash. So I'm glad that tests showed best results for this algorithm in Chrome and IE. Thanks to @rab for the code.

我希望看到使用对象{}的代码会胜出,因为它使用了散列。所以我很高兴在Chrome和IE中测试显示了这个算法的最佳结果。感谢@rab的代码。

#5


51  

I have since found a nice method that uses jQuery

我发现了一个使用jQuery的好方法

arr = $.grep(arr, function(v, k){
    return $.inArray(v ,arr) === k;
});

Note: This code was pulled from Paul Irish's duck punching post - I forgot to give credit :P

注意:这段代码是从保罗·爱尔兰的鸭子打击柱中提取出来的——我忘记把功劳记在下面了:P

#6


40  

One Liner, Pure JavaScript

With ES6 syntax

与ES6语法

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

列表=。filter(x, i, a) => a. indexof (x) = i)

x --> item in array
i --> index of item
a --> array reference, (in this case "list")

获取数组中的所有惟一值(删除重复值)

With ES5 syntax

与ES5的语法

list = list.filter(function (x, i, a) { 
    return a.indexOf(x) == i; 
});

Browser Compatibility: IE9+

IE9浏览器兼容性:+

#7


37  

Shortest solution with ES6: [...new Set( [1, 1, 2] )];

ES6最短解:[…]新集合([1,1,2])];

Or if you want to modify the Array prototype (like in the original question):

或者如果您想修改数组原型(如原始问题):

Array.prototype.getUnique = function() {
    return [...new Set( [this] )];
};

EcmaScript 6 is only partially implemented in modern browsers at the moment (Aug. 2015), but Babel has become very popular for transpiling ES6 (and even ES7) back to ES5. That way you can write ES6 code today!

EcmaScript 6目前在现代浏览器中只实现了一部分(2015年8月),但是Babel已经非常流行地将ES6(甚至ES7)传输回ES5。这样你今天就可以写ES6代码了!

If you're wondering what the ... means, it's called the spread operator. From MDN: «The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected». Because a Set is an iterable (and can only have unique values), the spread operator will expand the Set to fill the array.

如果你想知道…意思是,它叫做扩散运算符。从MDN:«扩展运算符允许在多个参数(用于函数调用)或多个元素(对于数组文本)的地方扩展表达式。因为集合是可迭代的(并且只能有唯一的值),所以spread操作符将展开集合来填充数组。

Resources for learning ES6:

参考资料学习ES6:

#8


31  

Simplest solution:

最简单的解决方案:

var arr = [1, 3, 4, 1, 2, 1, 3, 3, 4, 1];
console.log([...new Set(arr)]);

Or:

或者:

var arr = [1, 3, 4, 1, 2, 1, 3, 3, 4, 1];
console.log(Array.from(new Set(arr)));

#9


30  

The simplest, and fastest (in Chrome) way of doing this:

最简单、最快的(在Chrome中)方法是:

Array.prototype.unique = function() {
    var a = [];
    for (var i=0, l=this.length; i<l; i++)
        if (a.indexOf(this[i]) === -1)
            a.push(this[i]);
    return a;
}

Simply goes through every item in the array, tests if that item is already in the list, and if it's not, push to the array that gets returned.

只需遍历数组中的每个项,测试该项是否已经在列表中,如果不是,则推入返回的数组。

According to jsPerf, this function is the fastest of the ones I could find anywhere - feel free to add your own though.

根据jsPerf的说法,这个函数是我在任何地方都能找到的最快的函数——请随意添加您自己的函数。

The non-prototype version:

non-prototype版:

function uniques(arr) {
    var a = [];
    for (var i=0, l=arr.length; i<l; i++)
        if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
            a.push(arr[i]);
    return a;
}

Sorting

When also needing to sort the array, the following is the fastest:

当需要对数组进行排序时,以下是最快的:

Array.prototype.sortUnique = function() {
    this.sort();
    var last_i;
    for (var i=0;i<this.length;i++)
        if ((last_i = this.lastIndexOf(this[i])) !== i)
            this.splice(i+1, last_i-i);
    return this;
}

or non-prototype:

或non-prototype:

function sortUnique(arr) {
    arr.sort();
    var last_i;
    for (var i=0;i<arr.length;i++)
        if ((last_i = arr.lastIndexOf(arr[i])) !== i)
            arr.splice(i+1, last_i-i);
    return arr;
}

This is also faster than the above method in most non-chrome browsers.

在大多数非chrome浏览器中,这也比上面的方法快。

#10


29  

PERFORMANCE ONLY! this code is probably 10X faster than all the codes in here *works on all browsers and also has the lowest memory impact.... and more

性能只!这段代码可能是10倍的速度比所有的代码在这里*适用于所有浏览器和也有最低内存影响....和更多的

if you don't need to reuse the old array;btw do the necessary other operations before you convert it to unique here is probably the fastest way to do this, also very short.

如果您不需要重用旧的数组;顺便说一下,在将其转换为unique之前进行必要的其他操作,这可能是最快的方法,而且非常短。

var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];

then you can try this

然后你可以试试这个

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 1];

function toUnique(a, b, c) { //array,placeholder,placeholder
  b = a.length;
  while (c = --b)
    while (c--) a[b] !== a[c] || a.splice(c, 1);
  return a // not needed ;)
}
console.log(toUnique(array));
//[3, 4, 5, 6, 7, 8, 9, 0, 2, 1]

I came up with this function reading this article...

我想到了这个函数来阅读这篇文章……

http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/

http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/

I don't like the for loop. it has to many parameters.i like the while-- loop. while is the fastest loop in all browsers except the one we all like so much... chrome.

我不喜欢for循环。它有很多参数。我喜欢while循环。虽然是所有浏览器中最快的循环,除了我们都很喜欢的那个……铬。

anyway i wrote the first function that uses while.And yep it's a little faster than the function found in the article.but not enough.unique2()

我写了第一个用while的函数。是的,它比文章中的函数快一点。但不是enough.unique2()

next step use modern js.Object.keys i replaced the other for loop with js1.7's Object.keys... a little faster and shorter (in chrome 2x faster) ;). Not enough!.unique3().

下一步使用现代的js.Object。我用js1.7的objec .keys替换了另一个for循环。更快更短(在chrome 2x更快);不够! .unique3()。

at this point i was thinking about what i really need in MY unique function. i don't need the old array, i want a fast function. so i used 2 while loops + splice.unique4()

此时,我正在思考我的独特功能真正需要的是什么。我不需要旧的数组,我需要一个快速的函数。我用了2 while循环+ splice。unique4()

Useless to say that i was impressed.

说我印象深刻是没有用的。

chrome: the usual 150,000 operations per second jumped to 1,800,000 operations per second.

chrome:通常每秒15万次操作,现在增加到每秒180万次。

ie: 80,000 op/s vs 3,500,000 op/s

80000 op/s vs 3500000 op/s

ios: 18,000 op/s vs 170,000 op/s

ios: 18000 op/s vs 170000 op/s

safari: 80,000 op/s vs 6,000,000 op/s

safari: 80000 op/s vs 6000000 op/s

Proof http://jsperf.com/wgu or better use console.time... microtime... whatever

证明http://jsperf.com/wgu或使用console.time…microtime……无论

unique5() is just to show you what happens if you want to keep the old array.

unique5()只是向您展示如果您想保留旧的数组会发生什么。

Don't use Array.prototype if yu don't know what your doing. i just did alot of copy and past. Use Object.defineProperty(Array.prototype,...,writable:false,enumerable:false}) if you want to create a native prototype.example: https://*.com/a/20463021/2450730

不要使用数组。如果你不知道你在做什么,那就做原型吧。我只是复制了很多过去的东西。如果您想创建本机原型,请使用Object.defineProperty(Array.prototype,…,writable:false,enumerable:false)。例如:https://*.com/a/20463021/2450730

Demo http://jsfiddle.net/46S7g/

演示http://jsfiddle.net/46S7g/

NOTE: your old array is destroyed/becomestheunique after this operation.

注意:您的旧数组在此操作之后被销毁/变成惟一的。

if you can't read the code above ask, read a javascript book or here are some explainations about shorter code. https://*.com/a/21353032/2450730

如果您不能阅读上面的代码,请阅读javascript书籍,或者这里有一些关于更短代码的解释。https://*.com/a/21353032/2450730

some are using indexOf ... don't ... http://jsperf.com/dgfgghfghfghghgfhgfhfghfhgfh

有些人正在使用索引…不要……http://jsperf.com/dgfgghfghfghghgfhgfhfghfhgfh

for empty arrays

为空数组

!array.length||toUnique(array); 

#11


23  

Many of the answers here may not be useful to beginners. If de-duping an array is difficult, will they really know about the prototype chain, or even jQuery?

这里的许多答案可能对初学者不太有用。如果解duping一个数组是困难的,他们真的知道原型链,甚至jQuery吗?

In modern browsers, a clean and simple solution is to store data in a Set, which is designed to be a list of unique values.

在现代浏览器中,一个干净而简单的解决方案是将数据存储在一个集合中,这个集合被设计成唯一值的列表。

const cars = ['Volvo', 'Jeep', 'Volvo', 'Lincoln', 'Lincoln', 'Ford'];
const uniqueCars = Array.from(new Set(cars));

The Array.from is useful to convert the Set back to an Array so that you have easy access to all of the awesome methods (features) that arrays have. There are also other ways of doing the same thing. But you may not need Array.from at all, as Sets have plenty of useful features like forEach.

从数组转换回数组是非常有用的,这样您就可以很容易地访问数组所具有的所有很棒的方法(特性)。同样的事情还有其他的方法。但你可能根本不需要array,因为集合有很多有用的特性,比如forEach。

If you need to support old Internet Explorer, and thus cannot use Set, then a simple technique is to copy items over to a new array while checking beforehand if they are already in the new array.

如果您需要支持旧的Internet Explorer,因此不能使用Set,那么一种简单的技术就是将项目复制到一个新数组中,同时检查它们是否已经在新数组中。

// Create a list of cars, with duplicates.
var cars = ['Volvo', 'Jeep', 'Volvo', 'Lincoln', 'Lincoln', 'Ford'];
// Create a list of unique cars, to put a car in if we haven't already.
var uniqueCars = [];

// Go through each car, one at a time.
cars.forEach(function (car) {
    // The code within the following block runs only if the
    // current car does NOT exist in the uniqueCars list
    // - a.k.a. prevent duplicates
    if (uniqueCars.indexOf(car) === -1) {
        // Since we now know we haven't seen this car before,
        // copy it to the end of the uniqueCars list.
        uniqueCars.push(car);
    }
});

To make this instantly reusable, let's put it in a function.

为了使它能立即重复使用,我们把它放在一个函数中。

function deduplicate(data) {
    if (data.length > 0) {
        var result = [];

        data.forEach(function (elem) {
            if (result.indexOf(elem) === -1) {
                result.push(elem);
            }
        });

        return result;
    }
}

So to get rid of the duplicates, we would now do this.

为了去除重复的部分,我们现在要这样做。

var uniqueCars = deduplicate(cars);

The deduplicate(cars) part becomes the thing we named result when the function completes.

当函数完成时,deduplicate(cars)部分成为我们命名为result的对象。

Just pass it the name of any array you like.

只需将您喜欢的任何数组的名称传递给它。

#12


17  

This prototype getUnique is not totally correct, because if i have a Array like: ["1",1,2,3,4,1,"foo"] it will return ["1","2","3","4"] and "1" is string and 1 is a integer; they are different.

这个getUnique原型不是完全正确的,因为如果我有这样一个数组:[1]1 2 3 4 1" foo"它会返回[1" 2" 3" 4"]1是字符串1是整数;它们是不同的。

Here is a correct solution:

这里有一个正确的解决方案:

Array.prototype.unique = function(a){
    return function(){ return this.filter(a) }
}(function(a,b,c){ return c.indexOf(a,b+1) < 0 });

using:

使用:

var foo;
foo = ["1",1,2,3,4,1,"foo"];
foo.unique();

The above will produce ["1",2,3,4,1,"foo"].

上面将产生[1,2,3,4,1,"foo"]。

#13


16  

["Defects", "Total", "Days", "City", "Defects"].reduce(function(prev, cur) {
  return (prev.indexOf(cur) < 0) ? prev.concat([cur]) : prev;
 }, []);

[0,1,2,0,3,2,1,5].reduce(function(prev, cur) {
  return (prev.indexOf(cur) < 0) ? prev.concat([cur]) : prev;
 }, []);

#14


12  

Without extending Array.prototype (it is said to be a bad practice) or using jquery/underscore, you can simply filter the array.

没有扩展数组。原型(据说这是一个坏习惯)或使用jquery/下划线,您可以简单地过滤数组。

By keeping last occurrence:

通过保持最后的发生:

    function arrayLastUnique(array) {
        return array.filter(function (a, b, c) {
            // keeps last occurrence
            return c.indexOf(a, b + 1) < 0;
        });
    },

or first occurrence:

或者第一次出现:

    function arrayFirstUnique(array) {
        return array.filter(function (a, b, c) {
            // keeps first occurrence
            return c.indexOf(a) === b;
        });
    },

Well, it's only javascript ECMAScript 5+, which means only IE9+, but it's nice for a development in native HTML/JS (Windows Store App, Firefox OS, Sencha, Phonegap, Titanium, ...).

它只是javascript ECMAScript 5+,只代表IE9+,但是对于本地HTML/JS (Windows Store App, Firefox OS, Sencha, Phonegap, Titanium,…)的开发来说很不错。

#15


10  

That's because 0 is a falsy value in JavaScript.

这是因为在JavaScript中0是一个假值。

this[i] will be falsy if the value of the array is 0 or any other falsy value.

如果数组的值为0或任何其他错误值,则该[i]将是假的。

#16


10  

If you're using Prototype framework there is no need to do 'for' loops, you can use http://www.prototypejs.org/api/array/uniq like this:

如果您正在使用原型框架,那么就不需要做“for”循环,您可以使用http://www.prototypejs.org/api/array/uniq:

var a = Array.uniq();  

Which will produce a duplicate array with no duplicates. I came across your question searching a method to count distinct array records so after

这将产生一个没有副本的重复数组。我遇到了你的问题,搜索一个方法来计数不同的数组记录

uniq()

uniq()

I used

我使用

size()

尺寸()

and there was my simple result. p.s. Sorry if i misstyped something

结果很简单。如果我写错了,对不起

edit: if you want to escape undefined records you may want to add

编辑:如果你想转义未定义的记录,你可以添加

compact()

紧凑()

before, like this:

之前,就像这样:

var a = Array.compact().uniq();  

#17


9  

Array.prototype.getUnique = function() {
    var o = {}, a = []
    for (var i = 0; i < this.length; i++) o[this[i]] = 1
    for (var e in o) a.push(e)
    return a
}

#18


6  

I'm not sure why Gabriel Silveira wrote the function that way but a simpler form that works for me just as well and without the minification is:

我不知道为什么Gabriel Silveira用这种方式写这个函数但是一个简单的形式对我来说同样有效而且不需要缩小

Array.prototype.unique = function() {
  return this.filter(function(value, index, array) {
    return array.indexOf(value, index + 1) < 0;
  });
};

or in CoffeeScript:

或者在CoffeeScript:

Array.prototype.unique = ->
  this.filter( (value, index, array) ->
    array.indexOf(value, index + 1) < 0
  )

#19


6  

with es6 (and maintains order):

与es6(及维持秩序):

[...new Set(myArray)];

#20


5  

From Shamasis Bhattacharya's blog (O(2n) time complexity) :

从Shamasis Bhattacharya的博客(O(2n)时间复杂度):

Array.prototype.unique = function() {
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l;i+=1) o[this[i]] = this[i];
    for(i in o) r.push(o[i]);
    return r;
};

From Paul Irish's blog: improvement on JQuery .unique() :

来自Paul Irish的博客:JQuery改进。unique():

(function($){

    var _old = $.unique;

    $.unique = function(arr){

        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        } else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
})(jQuery);

// in use..
var arr = ['first',7,true,2,7,true,'last','last'];
$.unique(arr); // ["first", 7, true, 2, "last"]

var arr = [1,2,3,4,5,4,3,2,1];
$.unique(arr); // [1, 2, 3, 4, 5]

#21


5  

Finding unique Array values in simple method

在简单方法中找到唯一的数组值

function arrUnique(a){
  var t = [];
  for(var x = 0; x < a.length; x++){
    if(t.indexOf(a[x]) == -1)t.push(a[x]);
  }
  return t;
}
arrUnique([1,4,2,7,1,5,9,2,4,7,2]) // [1, 4, 2, 7, 5, 9]

#22


5  

To address the problem the other way around, it may be useful to have no duplicate while you load your array, the way Set object would do it but it's not available in all browsers yet. It saves memory and is more efficient if you need to look at its content many times.

要从另一个角度解决这个问题,在加载数组时没有重复是很有用的,就像Set对象那样,但并不是所有浏览器都可以使用它。它节省了内存,如果你需要多次查看它的内容,它会更有效。

Array.prototype.add = function (elem) {
   if (this.indexOf(elem) == -1) {
      this.push(elem);
   }
}

Sample:

示例:

set = [];
[1,3,4,1,2,1,3,3,4,1].forEach(function(x) { set.add(x); });

Gives you set = [1,3,4,2]

得到集合= [1,3,4,2]

#23


4  

You can also use jQuery

您还可以使用jQuery

var a = [1,5,1,6,4,5,2,5,4,3,1,2,6,6,3,3,2,4];

// note: jQuery's filter params are opposite of javascript's native implementation :(
var unique = $.makeArray($(a).filter(function(i,itm){ 
    // note: 'index', not 'indexOf'
    return i == $(a).index(itm);
}));

// unique: [1, 5, 6, 4, 2, 3]

Originally answered at: jQuery function to get all unique elements from an array?

最初的回答是:jQuery函数从数组中获取所有唯一的元素?

#24


4  

There is an easy way to resolve this task through ES6 - using Set:

有一个简单的方法来解决这个任务,通过ES6 -使用集合:

let arr = [1, 1, 2, 2, 3, 3];
let deduped = [...new Set(arr)] // [1, 2, 3]

#25


3  

If anyone using knockoutjs

如果有人使用knockoutjs

ko.utils.arrayGetDistinctValues()

BTW have look at all ko.utils.array* utilities.

顺便说一句,我看过所有的照片。数组*实用工具。

#26


3  

I found that serializing they hash key helped me get this working for objects.

我发现序列化它们的散列键可以帮助我在对象上工作。

Array.prototype.getUnique = function() {
        var hash = {}, result = [], key; 
        for ( var i = 0, l = this.length; i < l; ++i ) {
            key = JSON.stringify(this[i]);
            if ( !hash.hasOwnProperty(key) ) {
                hash[key] = true;
                result.push(this[i]);
            }
        }
        return result;
    }

#27


3  

You can also use sugar.js:

你也可以用sugar.js:

[1,2,2,3,1].unique() // => [1,2,3]

[{id:5, name:"Jay"}, {id:6, name:"Jay"}, {id: 5, name:"Jay"}].unique('id') 
  // => [{id:5, name:"Jay"}, {id:6, name:"Jay"}]

#28


3  

strange this hasn't been suggested before.. to remove duplicates by object key (id below) in an array you can do something like this:

奇怪的是,这是以前从未有人提过的。要在数组中删除重复的对象键(id),您可以这样做:

const uniqArray = array.filter((obj, idx, arr) => (
  arr.findIndex((o) => o.id === obj.id) === idx
)) 

#29


3  

We can do this using ES6 sets:

我们可以使用ES6集:

var duplicatedArray = [1,2,3,4,5,1,1,1,2,3,4];
var uniqueArray = Array.from(new Set(duplicatedArray));

//The output will be

/ /输出

uniqueArray = [1,2,3,4,5];

#30


2  

This will work.

这将工作。

function getUnique(a) {
  var b = [a[0]], i, j, tmp;
  for (i = 1; i < a.length; i++) {
    tmp = 1;
    for (j = 0; j < b.length; j++) {
      if (a[i] == b[j]) {
        tmp = 0;
        break;
      }
    }
    if (tmp) {
      b.push(a[i]);
    }
  }
  return b;
}

#1


1401  

With JavaScript 1.6 / ECMAScript 5 you can use the native filter method of an Array in the following way to get an array with unique values:

使用JavaScript 1.6 / ECMAScript 5,您可以使用数组的本机筛选方法来获取具有惟一值的数组:

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']

The native method filter will loop through the array and leave only those entries that pass the given callback function onlyUnique.

本机方法过滤器将循环遍历数组,只保留传递给定回调函数的条目only unique。

onlyUnique checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied.

只有在给定值是第一次出现时才进行唯一检查。如果没有,它必须是一个副本,并且不会被复制。

This solution works without any extra library like jQuery or prototype.js.

这个解决方案不需要任何额外的库,比如jQuery或prototype.js。

It works for arrays with mixed value types too.

它也适用于具有混合值类型的数组。

For old Browsers (<ie9), that do not support the native methods filter and indexOf you can find work arounds in the MDN documentation for filter and indexOf.

对于旧的浏览器( ),不支持本机方法过滤器和indexof的浏览器可以在mdn文档中找到过滤器和indexof的工作。

If you want to keep the last occurrence of a value, simple replace indexOf by lastIndexOf.

如果希望保留值的最后出现,可以使用lastIndexOf简单替换indexOf。

With ES6 it could be shorten to this:

有了ES6,它可以缩短为:

// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i); 

// unique is ['a', 1, 2, '1']

Thanks to Camilo Martin for hint in comment.

感谢卡米洛·马丁的评论暗示。

ES6 has a native object Set to store unique values. To get an array with unique values you could do now this:

ES6有一个本机对象集来存储惟一值。要获得一个具有独特值的数组,您可以这样做:

var myArray = ['a', 1, 'a', 2, '1'];

let unique = [...new Set(myArray)]; 

// unique is ['a', 1, 2, '1']

The constructor of Set takes an iterable object, like Array, and the spread operator ... transform the set back into an Array. Thanks to Lukas Liese for hint in comment.

Set的构造函数接受一个可迭代的对象,如Array和spread操作符…将这个集合转换为一个数组。感谢Lukas Liese的建议。

#2


451  

Updated answer for ES6/ES2015: Using the Set, the single line solution is:

ES6/ES2015的更新答案:使用Set,单线解决方案是:

var items = [4,5,4,6,3,4,5,2,23,1,4,4,4]
var uniqueItems = Array.from(new Set(items))

Which returns

它返回

[4, 5, 6, 3, 2, 23, 1]

As le_m suggested, this can also be shortened using spread operator , like

正如le_m所建议的,这也可以通过使用扩展运算符(例如)来缩短

var uniqueItems = [...new Set(items)]

#3


115  

You can also use underscore.js.

您还可以使用underscore.js。

console.log(_.uniq([1, 2, 1, 3, 1, 4]));
<script src="http://underscorejs.org/underscore-min.js"></script>

which will return:

这将返回:

[1, 2, 3, 4]

#4


85  

I realise this question has more than 30 answers already. But I've read through all the existing answers first and made my own research.

我知道这个问题已经有30多个答案了。但我先通读了所有现有的答案,并做了自己的研究。

I split all answers to 4 possible solutions:

我把所有的答案分成四种:

  1. Use new ES6 feature: [...new Set( [1, 1, 2] )];
  2. 使用新的ES6功能:[…新集合([1,1,2])];
  3. Use object { } to prevent duplicates
  4. 使用对象{}来防止重复。
  5. Use helper array [ ]
  6. 使用辅助数组[]
  7. Use filter + indexOf
  8. 使用过滤器+ indexOf

Here's sample codes found in answers:

以下是在答案中找到的示例代码:

Use new ES6 feature: [...new Set( [1, 1, 2] )];

function uniqueArray0(array) {
  var result = Array.from(new Set(array));
  return result    
}

Use object { } to prevent duplicates

function uniqueArray1( ar ) {
  var j = {};

  ar.forEach( function(v) {
    j[v+ '::' + typeof v] = v;
  });

  return Object.keys(j).map(function(v){
    return j[v];
  });
} 

Use helper array [ ]

function uniqueArray2(arr) {
    var a = [];
    for (var i=0, l=arr.length; i<l; i++)
        if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
            a.push(arr[i]);
    return a;
}

Use filter + indexOf

function uniqueArray3(a) {
  function onlyUnique(value, index, self) { 
      return self.indexOf(value) === index;
  }

  // usage
  var unique = a.filter( onlyUnique ); // returns ['a', 1, 2, '1']

  return unique;
}

And I wondered which one is faster. I've made sample Google Sheet to test functions. Note: ECMA 6 is not avaliable in Google Sheets, so I can't test it.

我想知道哪个更快。我做了谷歌样本表来测试函数。注意:ECMA 6在谷歌版中是不可用的,所以我不能测试它。

Here's the result of tests: 获取数组中的所有惟一值(删除重复值)

以下是测试结果:

I expected to see that code using object { } will win because it uses hash. So I'm glad that tests showed best results for this algorithm in Chrome and IE. Thanks to @rab for the code.

我希望看到使用对象{}的代码会胜出,因为它使用了散列。所以我很高兴在Chrome和IE中测试显示了这个算法的最佳结果。感谢@rab的代码。

#5


51  

I have since found a nice method that uses jQuery

我发现了一个使用jQuery的好方法

arr = $.grep(arr, function(v, k){
    return $.inArray(v ,arr) === k;
});

Note: This code was pulled from Paul Irish's duck punching post - I forgot to give credit :P

注意:这段代码是从保罗·爱尔兰的鸭子打击柱中提取出来的——我忘记把功劳记在下面了:P

#6


40  

One Liner, Pure JavaScript

With ES6 syntax

与ES6语法

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

列表=。filter(x, i, a) => a. indexof (x) = i)

x --> item in array
i --> index of item
a --> array reference, (in this case "list")

获取数组中的所有惟一值(删除重复值)

With ES5 syntax

与ES5的语法

list = list.filter(function (x, i, a) { 
    return a.indexOf(x) == i; 
});

Browser Compatibility: IE9+

IE9浏览器兼容性:+

#7


37  

Shortest solution with ES6: [...new Set( [1, 1, 2] )];

ES6最短解:[…]新集合([1,1,2])];

Or if you want to modify the Array prototype (like in the original question):

或者如果您想修改数组原型(如原始问题):

Array.prototype.getUnique = function() {
    return [...new Set( [this] )];
};

EcmaScript 6 is only partially implemented in modern browsers at the moment (Aug. 2015), but Babel has become very popular for transpiling ES6 (and even ES7) back to ES5. That way you can write ES6 code today!

EcmaScript 6目前在现代浏览器中只实现了一部分(2015年8月),但是Babel已经非常流行地将ES6(甚至ES7)传输回ES5。这样你今天就可以写ES6代码了!

If you're wondering what the ... means, it's called the spread operator. From MDN: «The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected». Because a Set is an iterable (and can only have unique values), the spread operator will expand the Set to fill the array.

如果你想知道…意思是,它叫做扩散运算符。从MDN:«扩展运算符允许在多个参数(用于函数调用)或多个元素(对于数组文本)的地方扩展表达式。因为集合是可迭代的(并且只能有唯一的值),所以spread操作符将展开集合来填充数组。

Resources for learning ES6:

参考资料学习ES6:

#8


31  

Simplest solution:

最简单的解决方案:

var arr = [1, 3, 4, 1, 2, 1, 3, 3, 4, 1];
console.log([...new Set(arr)]);

Or:

或者:

var arr = [1, 3, 4, 1, 2, 1, 3, 3, 4, 1];
console.log(Array.from(new Set(arr)));

#9


30  

The simplest, and fastest (in Chrome) way of doing this:

最简单、最快的(在Chrome中)方法是:

Array.prototype.unique = function() {
    var a = [];
    for (var i=0, l=this.length; i<l; i++)
        if (a.indexOf(this[i]) === -1)
            a.push(this[i]);
    return a;
}

Simply goes through every item in the array, tests if that item is already in the list, and if it's not, push to the array that gets returned.

只需遍历数组中的每个项,测试该项是否已经在列表中,如果不是,则推入返回的数组。

According to jsPerf, this function is the fastest of the ones I could find anywhere - feel free to add your own though.

根据jsPerf的说法,这个函数是我在任何地方都能找到的最快的函数——请随意添加您自己的函数。

The non-prototype version:

non-prototype版:

function uniques(arr) {
    var a = [];
    for (var i=0, l=arr.length; i<l; i++)
        if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
            a.push(arr[i]);
    return a;
}

Sorting

When also needing to sort the array, the following is the fastest:

当需要对数组进行排序时,以下是最快的:

Array.prototype.sortUnique = function() {
    this.sort();
    var last_i;
    for (var i=0;i<this.length;i++)
        if ((last_i = this.lastIndexOf(this[i])) !== i)
            this.splice(i+1, last_i-i);
    return this;
}

or non-prototype:

或non-prototype:

function sortUnique(arr) {
    arr.sort();
    var last_i;
    for (var i=0;i<arr.length;i++)
        if ((last_i = arr.lastIndexOf(arr[i])) !== i)
            arr.splice(i+1, last_i-i);
    return arr;
}

This is also faster than the above method in most non-chrome browsers.

在大多数非chrome浏览器中,这也比上面的方法快。

#10


29  

PERFORMANCE ONLY! this code is probably 10X faster than all the codes in here *works on all browsers and also has the lowest memory impact.... and more

性能只!这段代码可能是10倍的速度比所有的代码在这里*适用于所有浏览器和也有最低内存影响....和更多的

if you don't need to reuse the old array;btw do the necessary other operations before you convert it to unique here is probably the fastest way to do this, also very short.

如果您不需要重用旧的数组;顺便说一下,在将其转换为unique之前进行必要的其他操作,这可能是最快的方法,而且非常短。

var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];

then you can try this

然后你可以试试这个

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 1];

function toUnique(a, b, c) { //array,placeholder,placeholder
  b = a.length;
  while (c = --b)
    while (c--) a[b] !== a[c] || a.splice(c, 1);
  return a // not needed ;)
}
console.log(toUnique(array));
//[3, 4, 5, 6, 7, 8, 9, 0, 2, 1]

I came up with this function reading this article...

我想到了这个函数来阅读这篇文章……

http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/

http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/

I don't like the for loop. it has to many parameters.i like the while-- loop. while is the fastest loop in all browsers except the one we all like so much... chrome.

我不喜欢for循环。它有很多参数。我喜欢while循环。虽然是所有浏览器中最快的循环,除了我们都很喜欢的那个……铬。

anyway i wrote the first function that uses while.And yep it's a little faster than the function found in the article.but not enough.unique2()

我写了第一个用while的函数。是的,它比文章中的函数快一点。但不是enough.unique2()

next step use modern js.Object.keys i replaced the other for loop with js1.7's Object.keys... a little faster and shorter (in chrome 2x faster) ;). Not enough!.unique3().

下一步使用现代的js.Object。我用js1.7的objec .keys替换了另一个for循环。更快更短(在chrome 2x更快);不够! .unique3()。

at this point i was thinking about what i really need in MY unique function. i don't need the old array, i want a fast function. so i used 2 while loops + splice.unique4()

此时,我正在思考我的独特功能真正需要的是什么。我不需要旧的数组,我需要一个快速的函数。我用了2 while循环+ splice。unique4()

Useless to say that i was impressed.

说我印象深刻是没有用的。

chrome: the usual 150,000 operations per second jumped to 1,800,000 operations per second.

chrome:通常每秒15万次操作,现在增加到每秒180万次。

ie: 80,000 op/s vs 3,500,000 op/s

80000 op/s vs 3500000 op/s

ios: 18,000 op/s vs 170,000 op/s

ios: 18000 op/s vs 170000 op/s

safari: 80,000 op/s vs 6,000,000 op/s

safari: 80000 op/s vs 6000000 op/s

Proof http://jsperf.com/wgu or better use console.time... microtime... whatever

证明http://jsperf.com/wgu或使用console.time…microtime……无论

unique5() is just to show you what happens if you want to keep the old array.

unique5()只是向您展示如果您想保留旧的数组会发生什么。

Don't use Array.prototype if yu don't know what your doing. i just did alot of copy and past. Use Object.defineProperty(Array.prototype,...,writable:false,enumerable:false}) if you want to create a native prototype.example: https://*.com/a/20463021/2450730

不要使用数组。如果你不知道你在做什么,那就做原型吧。我只是复制了很多过去的东西。如果您想创建本机原型,请使用Object.defineProperty(Array.prototype,…,writable:false,enumerable:false)。例如:https://*.com/a/20463021/2450730

Demo http://jsfiddle.net/46S7g/

演示http://jsfiddle.net/46S7g/

NOTE: your old array is destroyed/becomestheunique after this operation.

注意:您的旧数组在此操作之后被销毁/变成惟一的。

if you can't read the code above ask, read a javascript book or here are some explainations about shorter code. https://*.com/a/21353032/2450730

如果您不能阅读上面的代码,请阅读javascript书籍,或者这里有一些关于更短代码的解释。https://*.com/a/21353032/2450730

some are using indexOf ... don't ... http://jsperf.com/dgfgghfghfghghgfhgfhfghfhgfh

有些人正在使用索引…不要……http://jsperf.com/dgfgghfghfghghgfhgfhfghfhgfh

for empty arrays

为空数组

!array.length||toUnique(array); 

#11


23  

Many of the answers here may not be useful to beginners. If de-duping an array is difficult, will they really know about the prototype chain, or even jQuery?

这里的许多答案可能对初学者不太有用。如果解duping一个数组是困难的,他们真的知道原型链,甚至jQuery吗?

In modern browsers, a clean and simple solution is to store data in a Set, which is designed to be a list of unique values.

在现代浏览器中,一个干净而简单的解决方案是将数据存储在一个集合中,这个集合被设计成唯一值的列表。

const cars = ['Volvo', 'Jeep', 'Volvo', 'Lincoln', 'Lincoln', 'Ford'];
const uniqueCars = Array.from(new Set(cars));

The Array.from is useful to convert the Set back to an Array so that you have easy access to all of the awesome methods (features) that arrays have. There are also other ways of doing the same thing. But you may not need Array.from at all, as Sets have plenty of useful features like forEach.

从数组转换回数组是非常有用的,这样您就可以很容易地访问数组所具有的所有很棒的方法(特性)。同样的事情还有其他的方法。但你可能根本不需要array,因为集合有很多有用的特性,比如forEach。

If you need to support old Internet Explorer, and thus cannot use Set, then a simple technique is to copy items over to a new array while checking beforehand if they are already in the new array.

如果您需要支持旧的Internet Explorer,因此不能使用Set,那么一种简单的技术就是将项目复制到一个新数组中,同时检查它们是否已经在新数组中。

// Create a list of cars, with duplicates.
var cars = ['Volvo', 'Jeep', 'Volvo', 'Lincoln', 'Lincoln', 'Ford'];
// Create a list of unique cars, to put a car in if we haven't already.
var uniqueCars = [];

// Go through each car, one at a time.
cars.forEach(function (car) {
    // The code within the following block runs only if the
    // current car does NOT exist in the uniqueCars list
    // - a.k.a. prevent duplicates
    if (uniqueCars.indexOf(car) === -1) {
        // Since we now know we haven't seen this car before,
        // copy it to the end of the uniqueCars list.
        uniqueCars.push(car);
    }
});

To make this instantly reusable, let's put it in a function.

为了使它能立即重复使用,我们把它放在一个函数中。

function deduplicate(data) {
    if (data.length > 0) {
        var result = [];

        data.forEach(function (elem) {
            if (result.indexOf(elem) === -1) {
                result.push(elem);
            }
        });

        return result;
    }
}

So to get rid of the duplicates, we would now do this.

为了去除重复的部分,我们现在要这样做。

var uniqueCars = deduplicate(cars);

The deduplicate(cars) part becomes the thing we named result when the function completes.

当函数完成时,deduplicate(cars)部分成为我们命名为result的对象。

Just pass it the name of any array you like.

只需将您喜欢的任何数组的名称传递给它。

#12


17  

This prototype getUnique is not totally correct, because if i have a Array like: ["1",1,2,3,4,1,"foo"] it will return ["1","2","3","4"] and "1" is string and 1 is a integer; they are different.

这个getUnique原型不是完全正确的,因为如果我有这样一个数组:[1]1 2 3 4 1" foo"它会返回[1" 2" 3" 4"]1是字符串1是整数;它们是不同的。

Here is a correct solution:

这里有一个正确的解决方案:

Array.prototype.unique = function(a){
    return function(){ return this.filter(a) }
}(function(a,b,c){ return c.indexOf(a,b+1) < 0 });

using:

使用:

var foo;
foo = ["1",1,2,3,4,1,"foo"];
foo.unique();

The above will produce ["1",2,3,4,1,"foo"].

上面将产生[1,2,3,4,1,"foo"]。

#13


16  

["Defects", "Total", "Days", "City", "Defects"].reduce(function(prev, cur) {
  return (prev.indexOf(cur) < 0) ? prev.concat([cur]) : prev;
 }, []);

[0,1,2,0,3,2,1,5].reduce(function(prev, cur) {
  return (prev.indexOf(cur) < 0) ? prev.concat([cur]) : prev;
 }, []);

#14


12  

Without extending Array.prototype (it is said to be a bad practice) or using jquery/underscore, you can simply filter the array.

没有扩展数组。原型(据说这是一个坏习惯)或使用jquery/下划线,您可以简单地过滤数组。

By keeping last occurrence:

通过保持最后的发生:

    function arrayLastUnique(array) {
        return array.filter(function (a, b, c) {
            // keeps last occurrence
            return c.indexOf(a, b + 1) < 0;
        });
    },

or first occurrence:

或者第一次出现:

    function arrayFirstUnique(array) {
        return array.filter(function (a, b, c) {
            // keeps first occurrence
            return c.indexOf(a) === b;
        });
    },

Well, it's only javascript ECMAScript 5+, which means only IE9+, but it's nice for a development in native HTML/JS (Windows Store App, Firefox OS, Sencha, Phonegap, Titanium, ...).

它只是javascript ECMAScript 5+,只代表IE9+,但是对于本地HTML/JS (Windows Store App, Firefox OS, Sencha, Phonegap, Titanium,…)的开发来说很不错。

#15


10  

That's because 0 is a falsy value in JavaScript.

这是因为在JavaScript中0是一个假值。

this[i] will be falsy if the value of the array is 0 or any other falsy value.

如果数组的值为0或任何其他错误值,则该[i]将是假的。

#16


10  

If you're using Prototype framework there is no need to do 'for' loops, you can use http://www.prototypejs.org/api/array/uniq like this:

如果您正在使用原型框架,那么就不需要做“for”循环,您可以使用http://www.prototypejs.org/api/array/uniq:

var a = Array.uniq();  

Which will produce a duplicate array with no duplicates. I came across your question searching a method to count distinct array records so after

这将产生一个没有副本的重复数组。我遇到了你的问题,搜索一个方法来计数不同的数组记录

uniq()

uniq()

I used

我使用

size()

尺寸()

and there was my simple result. p.s. Sorry if i misstyped something

结果很简单。如果我写错了,对不起

edit: if you want to escape undefined records you may want to add

编辑:如果你想转义未定义的记录,你可以添加

compact()

紧凑()

before, like this:

之前,就像这样:

var a = Array.compact().uniq();  

#17


9  

Array.prototype.getUnique = function() {
    var o = {}, a = []
    for (var i = 0; i < this.length; i++) o[this[i]] = 1
    for (var e in o) a.push(e)
    return a
}

#18


6  

I'm not sure why Gabriel Silveira wrote the function that way but a simpler form that works for me just as well and without the minification is:

我不知道为什么Gabriel Silveira用这种方式写这个函数但是一个简单的形式对我来说同样有效而且不需要缩小

Array.prototype.unique = function() {
  return this.filter(function(value, index, array) {
    return array.indexOf(value, index + 1) < 0;
  });
};

or in CoffeeScript:

或者在CoffeeScript:

Array.prototype.unique = ->
  this.filter( (value, index, array) ->
    array.indexOf(value, index + 1) < 0
  )

#19


6  

with es6 (and maintains order):

与es6(及维持秩序):

[...new Set(myArray)];

#20


5  

From Shamasis Bhattacharya's blog (O(2n) time complexity) :

从Shamasis Bhattacharya的博客(O(2n)时间复杂度):

Array.prototype.unique = function() {
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l;i+=1) o[this[i]] = this[i];
    for(i in o) r.push(o[i]);
    return r;
};

From Paul Irish's blog: improvement on JQuery .unique() :

来自Paul Irish的博客:JQuery改进。unique():

(function($){

    var _old = $.unique;

    $.unique = function(arr){

        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        } else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
})(jQuery);

// in use..
var arr = ['first',7,true,2,7,true,'last','last'];
$.unique(arr); // ["first", 7, true, 2, "last"]

var arr = [1,2,3,4,5,4,3,2,1];
$.unique(arr); // [1, 2, 3, 4, 5]

#21


5  

Finding unique Array values in simple method

在简单方法中找到唯一的数组值

function arrUnique(a){
  var t = [];
  for(var x = 0; x < a.length; x++){
    if(t.indexOf(a[x]) == -1)t.push(a[x]);
  }
  return t;
}
arrUnique([1,4,2,7,1,5,9,2,4,7,2]) // [1, 4, 2, 7, 5, 9]

#22


5  

To address the problem the other way around, it may be useful to have no duplicate while you load your array, the way Set object would do it but it's not available in all browsers yet. It saves memory and is more efficient if you need to look at its content many times.

要从另一个角度解决这个问题,在加载数组时没有重复是很有用的,就像Set对象那样,但并不是所有浏览器都可以使用它。它节省了内存,如果你需要多次查看它的内容,它会更有效。

Array.prototype.add = function (elem) {
   if (this.indexOf(elem) == -1) {
      this.push(elem);
   }
}

Sample:

示例:

set = [];
[1,3,4,1,2,1,3,3,4,1].forEach(function(x) { set.add(x); });

Gives you set = [1,3,4,2]

得到集合= [1,3,4,2]

#23


4  

You can also use jQuery

您还可以使用jQuery

var a = [1,5,1,6,4,5,2,5,4,3,1,2,6,6,3,3,2,4];

// note: jQuery's filter params are opposite of javascript's native implementation :(
var unique = $.makeArray($(a).filter(function(i,itm){ 
    // note: 'index', not 'indexOf'
    return i == $(a).index(itm);
}));

// unique: [1, 5, 6, 4, 2, 3]

Originally answered at: jQuery function to get all unique elements from an array?

最初的回答是:jQuery函数从数组中获取所有唯一的元素?

#24


4  

There is an easy way to resolve this task through ES6 - using Set:

有一个简单的方法来解决这个任务,通过ES6 -使用集合:

let arr = [1, 1, 2, 2, 3, 3];
let deduped = [...new Set(arr)] // [1, 2, 3]

#25


3  

If anyone using knockoutjs

如果有人使用knockoutjs

ko.utils.arrayGetDistinctValues()

BTW have look at all ko.utils.array* utilities.

顺便说一句,我看过所有的照片。数组*实用工具。

#26


3  

I found that serializing they hash key helped me get this working for objects.

我发现序列化它们的散列键可以帮助我在对象上工作。

Array.prototype.getUnique = function() {
        var hash = {}, result = [], key; 
        for ( var i = 0, l = this.length; i < l; ++i ) {
            key = JSON.stringify(this[i]);
            if ( !hash.hasOwnProperty(key) ) {
                hash[key] = true;
                result.push(this[i]);
            }
        }
        return result;
    }

#27


3  

You can also use sugar.js:

你也可以用sugar.js:

[1,2,2,3,1].unique() // => [1,2,3]

[{id:5, name:"Jay"}, {id:6, name:"Jay"}, {id: 5, name:"Jay"}].unique('id') 
  // => [{id:5, name:"Jay"}, {id:6, name:"Jay"}]

#28


3  

strange this hasn't been suggested before.. to remove duplicates by object key (id below) in an array you can do something like this:

奇怪的是,这是以前从未有人提过的。要在数组中删除重复的对象键(id),您可以这样做:

const uniqArray = array.filter((obj, idx, arr) => (
  arr.findIndex((o) => o.id === obj.id) === idx
)) 

#29


3  

We can do this using ES6 sets:

我们可以使用ES6集:

var duplicatedArray = [1,2,3,4,5,1,1,1,2,3,4];
var uniqueArray = Array.from(new Set(duplicatedArray));

//The output will be

/ /输出

uniqueArray = [1,2,3,4,5];

#30


2  

This will work.

这将工作。

function getUnique(a) {
  var b = [a[0]], i, j, tmp;
  for (i = 1; i < a.length; i++) {
    tmp = 1;
    for (j = 0; j < b.length; j++) {
      if (a[i] == b[j]) {
        tmp = 0;
        break;
      }
    }
    if (tmp) {
      b.push(a[i]);
    }
  }
  return b;
}