Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
JavaScript - Sort Array again using first column after order the second column with duplicates

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Replace this line

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

with:

return (a[1] < b[1]) ? 1 : -1;
about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!