Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

remove duplicates from array

for( var i = 0; i < arr.length-1; i++){
if ( arr[i] == arr[i+1]) {
arr.splice(i, 1);
arr2.splice(i, 1);
}

}

}

I cant seem to remove the duplicates the way I want it to be, i just want to remove a value if the next one is the same and instead I get a value of undefined when used for splice, i need another way around this any help?

Best Answer
0 Votes
1 REPLY 1

It looks like you are manipulating the original array during the loop, which can lead to the kinds of problems you are getting with undefined values. A good practice for working on arrays like this is to create a new array which can be filled with the items you want to keep. In your case it would be filled with only unique array items from the original array.

 

There is a good rundown of different ways to remove duplicate items in Javascript. The first one by using a for loop, however the Array filter method is the nicest one, I think!

 

Best Answer
0 Votes