Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{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);
console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading