how to find duplicates in an array and remove them using javascript?
-
What type variables will be in the array? Only strings?Pekka– Pekka2010-09-13 10:52:09 +00:00Commented Sep 13, 2010 at 10:52
-
sorry wasnt specific,i was thinking both string and integer arrays.manraj82– manraj822010-09-13 10:55:15 +00:00Commented Sep 13, 2010 at 10:55
-
possible duplicate of unique() for arrays in javascriptAndy E– Andy E2010-09-13 11:16:57 +00:00Commented Sep 13, 2010 at 11:16
Add a comment
|
3 Answers
To do this generically, you could use something like the following, which removes duplicates from the array in place. If you have an array that contains only strings or numbers, you could simplify this significantly.
var arrayContains = Array.prototype.indexOf ?
function(arr, val) {
return arr.indexOf(val) > -1;
} :
function(arr, val) {
var i = arr.length;
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
}
function removeDuplicates(arr, equals) {
var val, originalArr = arr.slice(0);
arr.length = 0;
for (var i = 0, len = originalArr.length; i < len; ++i) {
val = originalArr[i];
if (!arrayContains(arr, val)) {
arr.push(val);
}
}
return arr;
}
var arr = [1, 2, 2, 1, 3];
removeDuplicates(arr);
console.log(arr); // [1, 2, 3]
Comments
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;
}