Home > database >  JavaScript - Sort Array again using first column after order the second column with duplicates
JavaScript - Sort Array again using first column after order the second column with duplicates

Time:06-28

I'm working to a script to reoder an array with javascript. When I've a duplicate value on the second column, I would like to order this duplicate value by index order and push it on new array.

The aim is to transform array like this :

myarr = [ 
    [5, 7]
    [2, 8]
    [3, 7]
    ];
    var valeurcroiss = myarr.sort(compareSecondColumn);
    var valeurdecroiss = valeurcroiss.reverse();
    valeurdecroiss.length = 3;
    
    function compareSecondColumn(a, b) {
         if (a[1] === b[1]) {
             return 0;
         }
         else {
             return (a[1] < b[1]) ? -1 : 1;
        }
    }

Result that I have:

[
0: (2) [5, 7]
1: (2) [3, 7]
2: (2) [2, 8]
];

Result I would like to have:

[
0: (2) [2, 8]
1: (2) [3, 7]
2: (2) [5, 7]
];

Thank you for your help

CodePudding user response:

Replace this line

return (a[1] < b[1]) ? -1 : 1;

with:

return (a[1] < b[1]) ? 1 : -1;

CodePudding user response:

If there's a duplicate in the second column it'll already be arranged correctly if the first column is already arranged properly. So check for duplicates in index 0 and sort them out by index 1 and sort the rest by index 0.

const pairs = [[5, 7], [2, 8], [3, 7], [2, 6]];

let output = pairs.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);

console.log(output);

  • Related