Skip to content Skip to sidebar Skip to footer

JS Sort By Specific Sort Order

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(

Solution 1:

Your .sort() callback can do whatever it needs to do to figure out whether any given item should be before or after any other given item. So it can look up the index of the current item within your sortBy array and proceed accordingly:

const sortBy = ['b','a','c','e','d']
const data = ['a','d','e']

console.log( data.sort((a,b) => sortBy.indexOf(a) - sortBy.indexOf(b)) )

Calling .indexOf() multiple times during the sort would be kind of inefficient though, so you might want to turn you sortBy into an object before you start:

const sortBy = ['b','a','c','e','d']
const data = ['a','d','e']

const sortByObject = sortBy.reduce((a,c,i) => {
  a[c] = i
  return a
}, {})

console.log( data.sort((a,b) => sortByObject[a] - sortByObject[b]) )

(Note that the sort callback is not supposed to return a boolean value.)


Post a Comment for "JS Sort By Specific Sort Order"