Skip to content

Instantly share code, notes, and snippets.

@dorival
Last active August 29, 2015 13:58
Show Gist options
  • Save dorival/10086368 to your computer and use it in GitHub Desktop.
Save dorival/10086368 to your computer and use it in GitHub Desktop.
Remove unsorted array duplicates using vanilla JavaScript
// Sample array
var collection = [1, 3, 7, 9, 0, 2, 5, 3, 8, 10, 2, 11, 7, 1, 7, 4, 6, 8, 1, 0];
/* O(n²) complexity on worst case scenarios, but O(n) on best scenarios */
/* 2. Resize the array with two nested loops, but it goes one forward comparing and another backwards removing
The result is a faster interaction because we are removing duplicated ahead before Forward hits it */
function BackForwardUnique(arr){
for(var forward = 0; forward < arr.length; forward++){
for (var backward = arr.length - 1; backward > forward; backward--){
if (arr[forward] === arr[backward]){
arr.splice(backward, 1);
}
}
}
return arr;
}
/* 1. Make a O(n²) */
/* This prevents multiple resizes and instances per interaction. i.e.: splice */
function MoveOnlyUnique(arr){
var newArr = [], hasRepeated = false;
if(arr.length > 0){
newArr.push(arr[0]);
}
for (var i = 1; i < arr.length; i++){
hasRepeated = false;
for (var j = 0; j < newArr.length; j++){
if (arr[i] === newArr[j]){
hasRepeated = true;
break;
}
}
if (!hasRepeated){
newArr.push(arr[i]);
}
}
return newArr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment