Removing duplicate elements from an array

For example, I have an array like this:

var arr = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10] 

My goal is to drop the duplicate elements from the array and get the final array as follows:

 var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

How can this be done in JavaScript?

NOTE: the array is not sorted; values ​​can be arbitrary.

+52
javascript arrays
May 25 '13 at 8:28
source share
5 answers

This is simpler using Array.filter :

 var unique = arr.filter(function(elem, index, self) { return index === self.indexOf(elem); }) 
+180
May 25 '13 at 8:47
source share

Since the elements are still ordered, you do not need to build a map, there is a quick solution:

 var newarr = [arr[0]]; for (var i=1; i<arr.length; i++) { if (arr[i]!=arr[i-1]) newarr.push(arr[i]); } 

If your array were not sorted, you would use a map:

 var newarr = (function(arr){ var m = {}, newarr = [] for (var i=0; i<arr.length; i++) { var v = arr[i]; if (!m[v]) { newarr.push(v); m[v]=true; } } return newarr; })(arr); 

Please note that this is much faster than the accepted answer.

+13
May 25 '13 at 8:33
source share
 var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10]; function squash(arr){ var tmp = []; for(var i = 0; i < arr.length; i++){ if(tmp.indexOf(arr[i]) == -1){ tmp.push(arr[i]); } } return tmp; } console.log(squash(arr)); 

Working example http://jsfiddle.net/7Utn7/

Compatibility for indexOf in older browsers

+9
May 25 '13 at 8:37
source share

you can try this using jquery

  var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10]; var uniqueVals = []; $.each(arr, function(i, el){ if($.inArray(el, uniqueVals) === -1) uniqueVals.push(el); }); 
+6
May 25 '13 at 8:34
source share

Try removing duplicates from an array (simple) :

 Array.prototype.removeDuplicates = function (){ var temp=new Array(); this.sort(); for(i=0;i<this.length;i++){ if(this[i]==this[i+1]) {continue} temp[temp.length]=this[i]; } return temp; } 

Edit:

This code does not need to be sorted:

 Array.prototype.removeDuplicates = function (){ var temp=new Array(); label:for(i=0;i<this.length;i++){ for(var j=0; j<temp.length;j++ ){//check duplicates if(temp[j]==this[i])//skip if already present continue label; } temp[temp.length] = this[i]; } return temp; } 

(But not verified code!)

+5
May 25 '13 at 8:35
source share



All Articles