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:
[
{ 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.