0

I have an array of duplicate strings in no particular order or sorting.

const array = ["Train", "Car", "Car", "Train", "Bicycle", "Car", "Bicycle", "Car", "Train"]

I would like to sort the array in a specific order, specifically Train, Bicycle, Car.

So it should be sorted.

["Train", "Train", "Train", "Bicycle", "Bicycle", "Car", "Car", "Car", "Car"]

Also, if the array does not contain one of the string, it should still stick to the same order and just skip that string.

I've tried a bunch of different ways to sort it, with no luck.

halfer
  • 19,824
  • 17
  • 99
  • 186
rock_n_rolla
  • 337
  • 4
  • 13

2 Answers2

1

Simple order function could do your job

const array = [
  'Train',
  'Car',
  'Car',
  'Train',
  'Bicycle',
  'Car',
  'Bicycle',
  'Car',
  'Train',
];
const order = (str) => {
  if (str === 'Train') return 1;
  if (str === 'Bicycle') return 2;
  if (str === 'Car') return 3;
  return 0;
};

const ret = array.sort((x, y) => order(x) - order(y));
console.log(ret);
mr hr
  • 3,162
  • 2
  • 9
  • 19
1

You could take an object with the wanted order and sort by the values of the object.

const
    array = ["Train", "Car", "Car", "Train", "Bicycle", "Car", "Bicycle", "Car", "Train"],
    order = { Train: 1, Bicycle: 2, Car: 3 };

array.sort((a, b) => order[a] - order[b]);

console.log(...array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392