A sorting function that takes an array of samples. All sortable items which occur in the samples will be arranged in the order they occur there, all other items will be appended to the end in their original order or sorted with an optional provided comparision algorithm.
This can be useful when the items to sort are not completely known, but there are some well-known ones that should come first:
const pages = [ 'About', 'Products', 'Home', 'Contact', 'Carreer' ]
// No idea what pages exist, but if "Home" and "About" exist, they should come first
// Other pages should be kept in their original order
[...pages].sort(sortBySamples([ 'Home', 'About' ]))
// [ 'Home', 'About', 'Products', 'Contact', 'Carreer' ]
// Other pages should be kept in their original order, but "Contact" should come last
[...pages].sort(sortBySamples([ 'Home', 'About' ], (a, b) => {
if (a === 'Contact') {
return 1
} else if (b === 'Contact') {
return -1
} else {
return 0
}
}))
// [ 'Home', 'About', 'Products', 'Carreer', 'Contact' ]