Friday, October 16, 2015

Remove dupes from Javascript array

So imagine you have an array with a bunch of values, and you want to remove all of the duplicate values. There are a lot of different ways to do this... I was trying to come up with a way to do this without creating a new array. I was thinking that Array,indexOf() is probably just a loop that runs though an array from 0 until the end. If this assumption was true, I could catch dupes by looping through backwards, and checking if indexOf is not equal to the current iteration. This way I have a loop running from length to 0, and a built in loop running from 0 to length. Turns out, I was right. Here's the code.


function checkForDupes(arr){
for(var i = arr.length - 1; i >= 0; i--){
if(arr.indexOf(arr[i]) !== i){
arr.splice(i,1);
}
}
return arr;
}
view raw DupeChecker hosted with ❤ by GitHub

And a JSFiddle Demo!