ste*_*ute 1 javascript node.js lodash
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 }
];
Run Code Online (Sandbox Code Playgroud)
我试图根据数量以升序对这个数组的内容进行排序,所以我期望的结果应该是:
[
{ quantity: 1, cost: 0.5 },
{ quantity: 100, cost: 0.45 },
{ quantity: 500, cost: 0.35 },
{ quantity: 1000, cost: 0.25 }
]
Run Code Online (Sandbox Code Playgroud)
因此,我尝试使用lodash命令:
_.sortBy(quantityPricing, ['quantity']);
Run Code Online (Sandbox Code Playgroud)
但是不幸的是,该函数返回的结果似乎只按数量的第一位排序,例如:
{
"quantity": 1,
"cost": 0.5
},
{
"quantity": 100,
"cost": 0.45
},
{
"quantity": 1000,
"cost": 0.25
},
{
"quantity": 500,
"cost": 0.35
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么末尾会出现500,除非仅按第一位排序?当数组排序后,由于500应该排在100之后。
任何帮助将不胜感激。
Lodash sortBy不会修改原始数组,它应该返回一个新数组。您要打印原始阵列吗?
使用此代码进行测试,它可以正常工作:
var arr = _.sortBy(quantityPricing, 'quantity');
console.log(arr);
Run Code Online (Sandbox Code Playgroud)
结果:
[ { quantity: 1, cost: 0.5 },
{ quantity: 100, cost: 0.45 },
{ quantity: 500, cost: 0.35 },
{ quantity: 1000, cost: 0.25 } ]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7242 次 |
| 最近记录: |