Home > OS >  How to return a multidimensional array of numbers in descending order?
How to return a multidimensional array of numbers in descending order?

Time:01-18

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

CodePudding user response:

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.

CodePudding user response:

  1. Join the values using .map() and .join(''))
  2. Use .sort() and .reverse() to order by descending value
  3. Use .split() to break them into single digits again.

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

const joined = input.map(arr => arr.join(''));
const sorted = joined.sort().reverse();
const result = sorted.map(val => val.split(''));

console.log(result);

  •  Tags:  
  • Related