I have an array of objects like so:
var quantityPricing = [
{ quantity: 1, cost: 0.5 },
{ quantity: 100, cost: 0.45 },
{ quantity: 1000, cost: 0.25 },
{ quantity: 500, cost: 0.35 }
];
I am trying to sortBy the content of this array in ascending order based on the quantity, so the result I am expecting should be:
[
{ quantity: 1, cost: 0.5 },
{ quantity: 100, cost: 0.45 },
{ quantity: 500, cost: 0.35 },
{ quantity: 1000, cost: 0.25 }
]
I have therefore tried to use the lodash command:
_.sortBy(quantityPricing, ['quantity']);
But unfortunately the result which is returned by the function seem to be only sorted by the first digit in the quantity, for example:
{
"quantity": 1,
"cost": 0.5
},
{
"quantity": 100,
"cost": 0.45
},
{
"quantity": 1000,
"cost": 0.25
},
{
"quantity": 500,
"cost": 0.35
}
I do not understand why 500 comes at the end, unless it is sorting by the first digit only? As 500 should come after 100 once my array is sorted.
Any help would be greatly appreciated.
Lodash sortBy doesn't modify the original array and it should return a new array. Are you printing the original array?
Test with this code and it works:
var arr = _.sortBy(quantityPricing, 'quantity');
console.log(arr);
Result:
[ { quantity: 1, cost: 0.5 },
{ quantity: 100, cost: 0.45 },
{ quantity: 500, cost: 0.35 },
{ quantity: 1000, cost: 0.25 } ]
Your code should actually work.
https://jsbin.com/vepipafaha/edit?html,js,console,output
You probably have supplied string instead of number for quantity in your JSON Array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With