Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash SortBy object content

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.

like image 691
steeveroucaute Avatar asked Dec 06 '25 19:12

steeveroucaute


2 Answers

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 } ]
like image 115
iKoala Avatar answered Dec 08 '25 07:12

iKoala


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.

like image 33
drinchev Avatar answered Dec 08 '25 08:12

drinchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!