JS按对象属性排序对象数组(美元) [英] JS order array of objects by object property (dollars)

查看:22
本文介绍了JS按对象属性排序对象数组(美元)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了很长时间才弄清楚这个问题.我的 vuejs 应用程序中有一个对象数组,如下所示:

I am having a heck of a time figuring this one out. I have an array of objects in my vuejs app like so:

var food= [{'name':'apples','price':'222.30'},{'name':'bananas','price':'99.30'},{'name':'oranges','price':'199.30'}];

当我尝试按价格排序时,我同时尝试

When I try to sort by price, I am trying both

return food.sort((a, b) => (a.price> b.price) ? 1 : -1);
AND
return _.orderBy(food, 'price')

然而,这似乎将 99.30 美元的价格解释为高于 222.30 美元 - 我假设是因为 9 高于 2?

However it seems this interprets the price $99.30 as higher than $222.30 - I am assuming because 9 is higher than 2?

任何帮助将不胜感激!我也想知道是否有办法从大到小排序,反之亦然.

Any help would be appreciated! I am also wondering if there is a way to order largest to smallest and vice versa.

推荐答案

您必须将价格转换为数字并在排序回调中使用

You have to convert the price to a number and use in your sort callback

return food.sort((a, b) => parseFloat(a.price) -  parseFloat(b.price));

这篇关于JS按对象属性排序对象数组(美元)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆