Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

Extract price from string array and sort by price

New member
Joined
Feb 9, 2023
Messages
4
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.

Code:
let luxcar_data = ["Ferrari70", "Bugatti45", "McLaren17", "Lamborghini41", "Rolls52",  "Aston30", "Koenigsegg19", "Pagani28", "Lamborghini36", ...];
The outcome should look like this.

Code:
[{name: "McLaren", price: 17},  {name: "Koenigsegg, price: 19}, .... , {name: "Ferrari", price: 70}]
 
New member
Joined
Feb 9, 2023
Messages
4
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.

Code:
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);
console.log(res);
 
Top