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

160
Views
How to return a multidimensional array of numbers in descending order?

I am new to JS and I am tring to sort a multidimensional array and I want to return the array in descending order -

Input -

let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]

Expected Ouput

[[3,2,1],[3,1,2],[2,3,1],[2,1,3],[1,3,2],[1,2,3]]

I have tried sort

let result = input.sort((a, b) => a - b)

But I am getting the same array sent back to me

[[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]

I have also tried a for loop with the sort method

for(let i = 0; i < input.length; i++){
  let inputArr = input[i]
  let output = inputArr.sort((a,b) => a - b)

  console.log(output)
}

But I get returned

[1,2,3] 6 times (the length of the original array?)

How do I return the array values in descending order?

Thanks

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

0

You need to compare the subarray items against each other - .sort((a, b) -> a - b) makes no sense because a and b are arrays, and so can't be meaningfully subtracted from each other.

let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]];
input.sort((a, b) => {
  // Find the first index that's different between the two subarrays being compared
  const diffIndex = a.findIndex((itemA, i) => b[i] !== itemA);
   // Return the difference, so that the higher value will come first in the result
   // If no difference found, return 0 (so they will come next to each other)
  return diffIndex === -1 ? 0 : b[diffIndex] - a[diffIndex];
});
console.log(input);
  

That's assuming that the subarrays contain the same number of values, as it is in the example.

about 4 years ago · Juan Pablo Isaza Report

0

The sort operation expects numbers. You can apply the .sort() array method on input using concatenated inner array elements converted into a number - +arr.join('') - as in the following demo:

let input = [ [1,2,3], [1,3,2], [3,2,1], [3,1,2], [2,1,3], [2,3,1] ];

const sorted = input.sort( (a,b) => +b.join('') - +a.join('') );

console.log( sorted );
//OUTPUT: [ [3,2,1], [3,1,2], [2,3,1], [2,1,3], [1,3,2], [1,2,3] ]

NOTE

You may also use parseInt( arr.join('') ) in place of +arr.join('').

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!