Monday, May 9, 2011

Remove duplicates from an array using JavaScript

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:

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

javascript code:

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;
}

No comments:

Post a Comment