-2

The following multi-array is sorted randomly:

let arr = [[3, "C"], [2, "B"], [3, "Q"], [1, "A"], [2, "P"], [1, "O"]];

The intention is to sort it as:

arr = [[1, "O"], [1, "A"], [2, "P"], [2, "B"], [3, "Q"], [3, "C"]];

viewed as a table:

/*
col 1 | col 2         col 1 | col 2
  3   |   C             1   |   O    ˄
  2   |   B        |    1   |   A    ¦
-------------      |  -------------
  3   |   Q    =˃  |    2   |   P    ˄
  1   |   A        |    2   |   B    ¦
-------------      |  -------------
  2   |   P        ˅    3   |   Q    ˄
  1   |   O             3   |   C    ¦
*/

in another perspective I want to achieve what in a SQL query will be something like:

SELECT * FROM table
ORDER BY column1 ASC, column2 DESC

how to do that? or is there a better method instead of using Arrays? thanks!

2 Answers2

0

Just take two sort parameter with a function which works for numbers and strings.

const
    sort = (a, b) => (a > b) - (a < b),
    array = [[3, "C"], [2, "B"], [3, "Q"], [1, "A"], [2, "P"], [1, "O"]];

array.sort((a, b) => sort(a[0], b[0]) || sort(b[1], a[1]));

console.log(array);
 
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

const array = [[3, "C"], [2, "B"], [3, "Q"], [1, "A"], [2, "P"], [1, "O"]];

array.sort((a, b) => compareNumbers(a[0], b[0]) || compareStr(a[1], b[1]));

function compareNumbers(a, b) {
  return a - b;
}

function compareStr(a, b) {
  if (a>b) {
    return -1;
  }
  if (a<b) {
    return 1;
  }
  return 0;
}
console.log(array)
// existing sort function can also be converted to a function. Here, just to show sort() and comparision implementation.