In class today we were asked to write an algorithm.
Given an array, remove duplicate values:
- It should be stable, and shouldn't have to use an inner loop.
- Should be done in place, as best as possible
- No use of built in functions (I was only allowed to use
.push)
After wrestling with it for a while, this is what I came up with.
function remove_dupes(arr){
var seen = {};
var count = 0;
for( var i = 0; i < arr.length - count ; i++) {
arr[i] = arr[i+count];
if( seen[arr[i]] ) {
count++;
arr[i] = arr[i+count];
i--;
}
seen[arr[i]] = true;
}
arr.length = arr.length - count;
}
I have a bit of repeated code here and I feel that maybe the i-- isn't the best way to go.
Is there any way I could improve this code (without using built in functions)?