Remove duplicates from an array using JavaScript

Advertisement
Post Pic

Here is a simple and easily understandable snippet code, to remove duplicates from an existing array using JavaScript. You guys! might have come across in some situation where in which the array has got some duplicates and want to remove those duplicates to show up unique ones. Below simple JavaScript code does the same, initially the respective array has got some value like below:

1
var sampleArr=new Array(1,1,1,1,1,2,2,3,3,3,4,4,4);

And now your expecting output should be 1,2,3,4 right? yeah it does the same.

JavaScript Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var sampleArr=new Array(1,1,1,1,1,2,2,3,3,3,4,4,4); //Declare array
document.write(uniqueArr(sampleArr)); //Print the unique value
 
//Adds new uniqueArr values to temp array
function uniqueArr(a) {
 temp = new Array();
 for(i=0;i<a.length;i++){
  if(!contains(temp, a[i])){
   temp.length+=1;
   temp[temp.length-1]=a[i];
  }
 }
 return temp;
}
 
//Will check for the Uniqueness
function contains(a, e) {
 for(j=0;j<a.length;j++)if(a[j]==e)return true;
 return false;
}

You can customize accordingly instead of ‘document.write’ you can copy unique values to other array and proceed accordingly.

Related Entries...

You Might Like:

Advertisement

Please let us know your feedback about the article through the comments section below, we want to hear from you about our website. And your comment / advice may help us to serve you better in upcoming articles.

Thank You!
Vivekanand [Founder of DeveloperSnippets]

5 Responses

[...] which you would like to read: 1. Remove duplicates from an array using JavaScript 2. Check out the number of Occurrences using JavaScript 3. Adding a div, button to the body tag [...]

[...] If you want to same concept for one dimensional array that is simple array, then you can view this article for reference – Remove duplicates from an array using JavaScript [...]

10.30.08

thanks its a good code that work for me…

[...] to Developer Snippets for the code « jQuery SWFObject Plugin and [...]

10.30.08

var i,j,temp;
var arr=[8,33,29,2,68,3,75,68,46,2,29,1,78];
for(i=0;i<arr.length;i++)
{
for(j=i+1;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
temp=arr.splice(j,1)
alert(temp);
document.writeln(temp);
}
}

}
document.writeln("array without duplicates");
document.writeln(arr);

Leave Your Response

* Name, Email, Comment are Required

Write For Us

Online Sponsors

Start Foreign Exchange Trading today with the Forex Affiliate Program and also you can have access Online Forex News to know what happens every single moment.


Forex Floor


Switch to our mobile site