Your method relies on sorting, which may or may not be one of the reasons why you have run out of space / time.
The canonical way to remove duplicates is to save the key hash map (object in JS). The keys of the objects you receive will not necessarily be in the order you want; you do not indicate whether you want to organize the results as well, but they are now.
You can null
from the original array, since you no longer require it; when he gets the engine assembled before JS though.
You can remove duplicates “in place” by storing the “current index” in the sorted array and increasing it only when you move the non-duplicated element “down” from the counter index, and then crop the returned array.
The combination of the last two methods should mean that in general you will only have one array with a valid reference.
Change the example. Setting length
explicit, since .slice()
creates a new array.
var have = {}; var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7]; arr = arr.sort(); for (var rIdx = 0, i = 0; i < arr.length; i++) { if (have[arr[i]]) { arr[rIdx++] = arr[i]; } else { have[arr[i]] = true; } } arr.length = rIdx; console.log(arr);
source share