Sort plus map vs direct array insertion (v2)

Revision 2 of this benchmark created on


Setup

const generateShuffledArray = (lim) => {
    // Generate an array of numbers from 0 to lim-1
    let numbers = Array.from({length: lim}, (_, index) => index);

    // Shuffle the numbers array using the Fisher-Yates (Durstenfeld) shuffle algorithm
    for (let i = numbers.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [numbers[i], numbers[j]] = [numbers[j], numbers[i]];
    }

    // Pair each 'line_n' with a unique shuffled number
    let resultArray = numbers.map((num, index) => [`line_${index + 1}`, num.toString()]);

    return resultArray;
}

const lim = 10000; // Set the limit, adjust as necessary
const my_array = generateShuffledArray(lim);
console.log(my_array);

Test runner

Ready to run.

Testing in
TestOps/sec
Sort plus map
const res = my_array.sort((a, b) => a[1] - b[1]).map(pair => pair[0]);
console.log(res);
ready
Insertion into existing array
const res = [];
my_array.forEach(pair => res[pair[1]] = pair[0]);
console.log(res);
ready
Reduce to array
const res = my_array.reduce((acc, pair) => (acc[pair[1]] = pair[0], acc), []);
console.log(res)
ready
Object.values of fromEntries
const res = Object.values(Object.fromEntries(my_array.map(([v, k]) => [k, v])));
console.log(res);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.