I'm trying to sort an array [3,3,2,1,3,2,2,2,1]
to [1,1,3,3,3,2,2,2,2]
.
I'm trying to handle it using object, using the number as key, and the occurrence as value.
const sortNums = (arr) => {
const result = {}
for (let i = 0; i < arr.length; i++) {
const num = result[arr[i]] || 0;
result[arr[i]] = num + 1;
}
//The above will gives me { '1': 2, '2': 4, '3': 3 }
//How to convert back to array?
}
console.log(sortNums([3,3,2,1,3,2,2,2,1]))
Of course I can use the Object.entries
to map back to an array, but then the entire algorithm will be consider O(n^2) right? I'm trying to explore if it can be achieve in O(n) instead.
Or I shouldn't use object to begin with?