Reputation: 69
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.
Upvotes: 3
Views: 13162
Reputation: 34367
Your code actually does work (as pointed out by @drinchev).
Paste this code and hit return:
_.sortBy([
{ quantity: 1, cost: 0.5 },
{ quantity: 100, cost: 0.45 },
{ quantity: 1000, cost: 0.25 },
{ quantity: 500, cost: 0.35 }
], ['quantity']);
It will look like this:
Upvotes: 1
Reputation: 880
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 } ]
Upvotes: 7
Reputation: 19591
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.
Upvotes: 2