steeveroucaute
steeveroucaute

Reputation: 69

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.

Upvotes: 3

Views: 13162

Answers (3)

Beau Smith
Beau Smith

Reputation: 34367

Your code actually does work (as pointed out by @drinchev).

  1. Go to https://lodash.com/docs/ (which has lodash loaded as a global variable)
  2. Open your browser's Javascript console.
  3. 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:

sortBy() example

Upvotes: 1

iKoala
iKoala

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

Ivan Drinchev
Ivan Drinchev

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

Related Questions