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

sort an array of arrays based on another array

How can I sort an array of arrays based on another array?

Example:

const dataset = [
  [ 'red', [{name: 'Apple car'}] ], 
  [ 'blue', [{name: 'Toothpiece'}] ],
  [ 'orange', [{name: 'Sun'}] ],
  [ 'yellow', [{name: 'Cat'}] ], 
] 
const order = ['blue', 'yellow', 'red', 'orange']

const sortedDataset = sortArrayBasedOnAnother(dataset, order)
// [
//   [ 'blue', [{name: 'Toothpiece'}] ],
//   [ 'yellow', [{name: 'Cat'}] ],
//   [ 'red', [{name: 'Apple car'}] ], 
//   [ 'orange', [{name: 'Sun'}] ],
// ] 

This is what I tried but it doesn’t work:

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

function sortArrayBasedOnAnother(dataset, order) {
  return order.filter((value) => dataset[0].includes(value))
}

note: dataset is an array of arrays because it’s computed from groupBy of Lodash

>Solution :

Array.sort() can pass in a custom compare function then the custom function will check the positions of the elements in the second array and use that to determine the sorting order.

function sortArrayBasedOnAnother(dataset, order) {
  dataset.sort((a, b) => {
    let indexA = order.indexOf(a[0]);
    let indexB = order.indexOf(b[0]);
    return indexA - indexB; //will return negative, 0, or positive value depending on their positions inorder array
  });
  return dataset;
}

then calling the function with your dataset and order arrays and it will return the sorted dataset.

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