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
I would try it like this:
The
colorIndexMap
maps the colors from theorder
array to their corresponding index positions. Thesort()
function expects a comparison function that takes two elements (a
andb
) 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 ina
, same withb
. By subtracting these values, the comparison function determines the order: If the result is negative, it means thata
should come beforeb
. If it’s positive,b
should come beforea
. If it’s zero, the order remains unchanged.You can just use
sort
method and then useindexOf
or each element from theorder
array to sort thedataset
.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.then calling the function with your dataset and order arrays and it will return the sorted dataset.
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:(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 theorder
array, the corresponding item will not be included in the result.