In the class today, we were asked to write an algorithm.
Given the array, remove duplicate values:
- It must be stable and should not use the inner loop.
- Should be done in place as best as possible
- No built-in functions (I was allowed to use
.push)
After struggling with him 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;
}
Working jsbin
I have a bit of duplicate code here, and I feel that maybe i--not the best way.
Is there a way to improve this code (without using the built-in functions)?
source
share