Is there a unique () function in javascript to remove similar elements in an array of numbers?

I have an array of numbers, for example: [1, 4, 7, 1, 2, 1, 3, 1, 4].

I would like to remove duplicate elements and sort the result, i.e. desired result: [1, 2, 3, 4, 7].

Are there any built-in Javascript / jQuery functions for this, or should I write my own?

+7
javascript jquery arrays unique
source share
4 answers

No, there is nothing built in. In addition, you need to know that the default sorting is lexical, so [9, 1, 10].sort() will return [1, 10, 9] .

The following will sort and remove duplicates from the array of numbers in place:

 function sortAndRemoveDuplicates(arr) { arr.sort( function(a, b) { return a - b; } ); var copy = arr.slice(0); arr.length = 0; for (var i = 0, len = copy.length; i < len; ++i) { if (i == 0 || copy[i] != copy[i - 1]) { arr.push(copy[i]); } } return arr; } var arr = [1, 4, 7, 1, 2, 1, 3, 10, 1, 4, 10]; sortAndRemoveDuplicates(arr); console.log(arr); // [1, 2, 3, 4, 7, 10] 
+8
source share

a subtree library is great for all of these tricks; I love him and I can’t live without him!

Once you declare it, you call its functions with an underscore, for example:

 _.uniq([1, 4, 7, 1, 2, 1, 3, 1, 4]); => [1, 4, 7, 2, 3] 

If you want it to be sorted:

 _.uniq([1, 4, 7, 1, 2, 1, 3, 1, 4]).sort(); => [1, 2, 3, 4, 7] 

On the page above:

"Underscore provides 60-odd functions that support both normal functional suspects: map, select, invoke, and more specialized helpers: function bindings, javascript templates, deep equality testing, etc."

+4
source share
 Array.prototype.unique = function(){ for(var i = 0; i < this.length; i++){ if( this.indexOf(this[i], i+1) != -1 ){ this.splice(i,1); i--; } } return this.sort(); } var x = [1,'x', 4, 7, 1, 2, 1,'x', 3, 1, 4]; x.unique() // [1, 2, 3, 4, 7, "x"] 
+1
source share

As with JavaScript 1.6, array.filter () can be used to remove duplicate values:

 [1, 4, 7, 1, 2, 1, 3, 1, 4] .filter(function (value, index, self) { return self.indexOf(value) === index; }); 

returns

 [1, 4, 7, 2, 3] 

What's good about the filter is that it works with all types of values ​​in an array:

 [1, "d", 4, "e", 7, "e", 1, "a", 2, "d", 1, "b", 3, "c", 1, "e", 4] .filter(function (value, index, self) { return self.indexOf(value) === index; }); 

returns

 [1, 2, 3, 4, 7, "a", "b", "c", "d", "e"] 
+1
source share

All Articles