I have a task to sort an array of random numbers by a certain order which is given from another array. All the other elements which could not be sorted should land at the end of the result array:
const array = [6,1,2,3,4,5]
const sortOrder = [3,2,1]
const shouldSortTo = [3,2,1,6,4,5]
I've got the following solution :
array.sort((a,b)=> {
if(sortOrder.indexOf(a) === -1 && sortOrder.indexOf(b) > -1 ) {
return 1
}
if(sortOrder.indexOf(a) > -1 && sortOrder.indexOf(b) === -1 ) {
return -1
}
return sortOrder.indexOf(a) - sortOrder.indexOf(b)
})
It works but I get the feeling that it's not easy to read or understand. Is there a better or shorter way to do it?