I am trying to sort an array of objects and the sorting will be done based on property which will be dynamic
I have an array
const fruitDetails = [
{item: "Berry", qty: "651042446", stockDate: "2021-09-20"},
{item: "Apple", qty: "23222", stockDate: "2023-08-10"},
{item: "Kiwi", qty: "132345", stockDate: "2022-10-23"}
];
Now the sorting could be of on item, qty or stockDate
A function to sort this array of objects with dynamic property
function sortedData(column) {
return fruitDetails.sort((a, b) => {
if (a[column].toLowerCase() > b[column].toLowerCase()) {
return 1;
}
if (a[column].toLowerCase() < b[column].toLowerCase()) {
return -1;
}
return 0;
});
}
console.log(sortedData("item"));
console.log(sortedData("qty"));
console.log(sortedData("stockDate"));
If you check the console output the sorted value for item and stockDate is correct but the qty sorted value is incorrect.
This is the console output for qty:
[{
item: "Kiwi",
qty: "132345",
stockDate: "2022-10-23"
}, {
item: "Apple",
qty: "23222",
stockDate: "2023-08-10"
}, {
item: "Berry",
qty: "651042446",
stockDate: "2021-09-20"
}]
The qty value 23222 is smaller than the 132345 so Apple should be 1st, Kiwi 2nd and Berry 3rd.
I am adding the jsfiddle link for reference.
Please let me know what I am doing wrong here, thank you 🙂
2
Answers
You can use regular expressions to test for numbers, then you would subtract the numbers (converted from strings) as you normally would when sorting numbers. Otherwise use the
String#localCompare
method as follows; strings and "date strings" in the format provided should sort fine with.localeCompare()
: