Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get sorted index of min values of 2d array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  `[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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading