Search code examples
javascriptarrayssorting

JS create array from a sorted array of pairs


I have this array of pairs in JS :

var my_array = [['line_1','2'],['line_2','3'],['line_3','5'],['line_4','1'],['line_5','4'],]

I would like to sort this array by values and then create a new array with only the sorted keys.

Expected result :

['line_4','line_1','line_2','line_5','line_3']

I tried to sort by using this :

var my_sorted_array = Object.values(my_array).sort((a, b) => a[1] - b[1])

But I don't know how to do the final step and I assume there is a better way to do this in pure JS.

Thanks


Solution

  • You have several methods. If you have a '0' and no gaps, you can use the second method here, which seems to be faster than sort plus map

    const start1 = performance.now();
    const res1 = my_array
      .sort((a, b) => a[1] - b[1])
      .map(pair => pair[0]);
    const end1 = performance.now();  
    console.log("1",`Execution time: ${end1 - start1} milliseconds`);
    
    const start2 = performance.now();
    const res2 = [];
    my_array
      .forEach(pair => res2[pair[1]] = pair[0]);
    const end2 = performance.now();  
    console.log("2",`Execution time: ${end2 - start2} milliseconds`);
    
    const start3 = performance.now();   
    const res3 = my_array
      .reduce((acc, pair) => (acc[pair[1]] = pair[0], acc), []);
    const end3 = performance.now();  
    console.log("3",`Execution time: ${end3 - start3} milliseconds`);
    
    const start4 = performance.now();   
    const res4 = Object.values(Object.fromEntries(my_array.map(([v, k]) => [k, v])));
    const end4 = performance.now();  
    console.log("4",`Execution time: ${end4 - start4} milliseconds`);
    <script>
    const lim = 10000; // Set the limit, adjust as necessary
    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 my_array = generateShuffledArray(lim);
    </script>

    Here is a jsperf, I hope I set it up correctly

    https://jsperf.app/pazuhe/2

    enter image description here