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.

1
  • Array.sort(comparator)? Commented Nov 7, 2020 at 19:02

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.