having 2d number array like;
const arr = [
[1, 5, 9],
[2, 7, 8],
[3, 0, 6],
];
what is the simplest way to get sorted array of array indexes where sort critera is values of original 2d array?
result should be:
`[2,1]`, // (value=0)
`[0,0]`, // (value=1)
`[2,0]`, // (value=2)
`[0,1]`, // (value=3)
...
btw, actual values are floats not that it matters.
but complexity does matter as loop runs on each frame.
>Solution :
You could get the indices first and sort them by the value of the matrix.
const
array = [[1, 5, 9], [2, 7, 8], [3, 0, 6]],
result = array
.flatMap((a, i) => a.map((_, j) => [i, j]))
.sort((a, b) => array[a[0]][a[1]] - array[b[0]][b[1]]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }