Monday, December 23, 2013

Remove duplicates in an array in Javascript

If you follow this approach, you need to create another array and if you have performance limitations you need to consider that.

This algorithm will be o(n)complexity in which n is the length.

With jQuery:

 var newArray = []; 
 var array=["amir", "amir", "rahnama", 1, 1]; 
 var newArray = [];

 $.each(array, function(i, element) { 
   if ($.inArray(element, newArray) === -1) {
       newArray.push(region); 
   }
 });

 console.log(newArray); // ["amir", "rahnama", 1];

Vanila Javascript:

 var newArray = []; 
 var array=["amir", "amir", "rahnama", 1, 1]; 
 var newArray = [];

 array.forEach(function(i, element) { 
   if (newArray.indexOf(element) === -1) { 
      newArray.push(region); 
   }
 });
 console.log(newArray); // ["amir", "rahnama", 1];

1 comment: