I need to sort my data by a specific order as shown below.
const sortBy = ['b','a','c','e','d']
const data = ['a','d','e']
I know how to sort by asscending/descending
console.log(data.sort((a, b) => a > b)) //["a", "d", "e"]
console.log(data.sort((a, b) => a < b)) //["e", "d", "a"]
But is it possible using .sort
to sort in a specific order?
eg below my desired order is sortBy
I am currently getting this to work by creating an array of common items between my sort array and my data.
const commonItems = getCommonItemsInArrays(sortBy,data)
console.log(commonItems.map(item => item)) //["a", "e", "d"]
function getCommonItemsInArrays(array1,array2){
return array1.filter(n => array2.indexOf(n) >= 0)
}
This seems to be working ok but I was wondering if there was a way to handle this via sort
?