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

How can I use the sort function to sort the object's elements in order by name and extract the values?

I have an array of objects called inje. I want to put in the answer in numerical order according to the last number of the name property of inje.

When I use sort() the order does not change. How do I fix my code?

const inje = [
  { name: "farm3", },
  { name: "farm1", },
  { name: "farm2", },
]

const answer = inje.sort(); // doesn't work.

Expected output:

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: "farm1", },
  { name: "farm2", },
  { name: "farm3", },
]

>Solution :

To do what you require you need to provide your own function to sort() which accepts two objects in the array and compares them. You can use a regular expression to extract the number at the end of the name string before making the comparison. Try this:

const inje = [
  { name: "farm3" },
  { name: "farm1" },
  { name: "farm2" }
]

const output = inje.sort((a, b) => {
  let aNum = +a.name.match(/\d+$/)[0];
  let bNum = +b.name.match(/\d+$/)[0];
  return aNum > bNum ? 1 : -1;
}); 

console.log(output);

A couple of things to note here. Firstly, this code assumes that there is always a number at the end of the value. If this isn’t the case you’ll need to add some guard clauses to handle that.

Also, be careful not to add trailing commas to your objects where they’re not required. Check the difference between your original inje object and the example above for what I mean.

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