简体   繁体   中英

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.

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.

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()示例

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM