I’m experimenting with sorting large arrays of unique integers in JavaScript and came up with a simple approach. I’m curious if it’s a recognized pattern or if there are potential pitfalls I might be missing.
Here’s the code I’m using:
function sortArr(arr) {
const sorted = [];
arr.forEach(el => sorted[el] = el);
return sorted.filter(el => el);
}
function getRandomArray(length, max = length * 10) {
const set = new Set();
while (set.size < length) {
set.add(Math.floor(Math.random() * max) + 1);
}
return [...set];
}
const arr = getRandomArray(100000);
console.log(sortArr(arr));
How it works:
Each number from the array is placed at the index equal to its value in a new array.
Then they are filtered out of empty slots to get the sorted array.
Questions:
-
Are there potential performance or memory issues with this approach in JavaScript, especially with large arrays or large maximum values?
-
Would this be practical for production code, or is it more of a coding experiment?
Any feedback or references to similar approaches would be appreciated!
I was trying to sort a large array of unique integers efficiently in JavaScript. I wanted to see if placing each element at its index in a new array and then filtering empty slots would produce a correctly sorted array, and whether this approach is efficient compared to built-in sort or counting sort.
I expected the code to return a sorted array in ascending order. I also expected it to run relatively fast for large arrays and use a reasonable amount of memory.
