Extract price from string array and sort by price

I need help determining the best way to extract the price value out of the strings in the array received from the API, and then reorder the array based on the lowest price values.

These are some of the data that I received from the API.

let luxcar_data = ["Ferrari70", "Bugatti45", "McLaren17", "Lamborghini41", "Rolls52",  "Aston30", "Koenigsegg19", "Pagani28", "Lamborghini36", ...];

The outcome should look like this.

[{name: "McLaren", price: 17},  {name: "Koenigsegg, price: 19}, .... , {name: "Ferrari", price: 70}]

>Solution :

String#match can be used to extract the name and price. Array#map can be applied to transform each element of the array to an object with the name and price. Then, directly call Array#sort and substract the prices in the compare function.

let arr = ["Ferrari70", "Bugatti45", "McLaren17", "Lamborghini41", "Rolls52",  "Aston30", "Koenigsegg19", "Pagani28", "Lamborghini36"];
let res = arr.map(s => {
  const [, name, price] = s.match(/([a-z]+)(\d+)/i);
  return {name, price};
}).sort((a, b) => a.price - b.price);

Leave a Reply