How to sort in specific order - array prototype(not by value or by name)

Viewed 855

I wish to sort an array of three strings in a specific order.

book, car and wheel.

I can receive these strings in any order. There may be one or more strings - max three

I would like to sort the strings in the following exact order if one or more strings are received.

wheel, book, car

assume the property name is name...

I tried something like this:

myitem.sort((a, b) => {
        if(a.name === 'wheel')
          return 1;
        if(a.name === 'book' && b.name === 'car')
          return 1;

        return -1;
4 Answers

Another option: indexOf. Undefined values show at the top of the list, but those don't exist. Probably slower than object with index values, but probably easier to maintain if the order changes, especially of the list gets large.

indexOfSort = (a, b) => {
  const order = [
    "wheel",
    "book",
    "car"
  ];
  return order.indexOf(a) - order.indexOf(b);
}

console.log(
['foo', 'car', 'book', 'wheel'].sort(indexOfSort)
);

Related