skip to Main Content

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:

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

4

Answers


  1. I would try it like this:

    function sortArrayBasedOnAnother(dataset, order) {
      const colorIndexMap = {};
      for (let i = 0; i < order.length; i++) {
        colorIndexMap[order[i]] = i;
      }
    
      dataset.sort((a, b) => colorIndexMap[a[0]] - colorIndexMap[b[0]]);
      return dataset;
    }
    

    The colorIndexMap maps the colors from the order array to their corresponding index positions. The sort() function expects a comparison function that takes two elements (a and b) from the array and returns a negative, zero, or positive value to determine the order. colorIndexMap[a[0]] retrieves the index position of the color in a, same with b. By subtracting these values, the comparison function determines the order: If the result is negative, it means that a should come before b. If it’s positive, b should come before a. If it’s zero, the order remains unchanged.

    Login or Signup to reply.
  2. You can just use sort method and then use indexOf or each element from the order array to sort the dataset.

    const dataset = [
      [ 'red', [{name: 'Apple car'}] ], 
      [ 'blue', [{name: 'Toothpiece'}] ],
      [ 'orange', [{name: 'Sun'}] ],
      [ 'yellow', [{name: 'Cat'}] ], 
    ] 
    const order = ['blue', 'yellow', 'red', 'orange']
    
    dataset.sort(([a], [b]) => order.indexOf(a) - order.indexOf(b))
    
    console.log(dataset)
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. First create a "key → item" map so that you can retrieve items by their keys, then iterate the order array and use that map to build the result:

    const map = {};
    
    for (let item of dataset) {
        map[item[0]] = item;
    }
    
    const result = [];
    
    for (let key of order) {
        if (map[key]) {
            result.push(map[key]);
        }
    }
    

    (alternatively, for map, you may consider to use a Map object rather than a plain object)

    Note that only items present in the order array will be included, i.e. if a key is missing from the order array, the corresponding item will not be included in the result.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search