尝试先按数字对数组进行排序,然后按字母对数组进行排序 [英] Trying to sort array by numbers first and then letters last

查看:254
本文介绍了尝试先按数字对数组进行排序,然后按字母对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对数组进行排序.我正在尝试按"itemCommodity"进行排序.我只需要先按数字排序,然后再按字母排序.例如:

I am trying to sort an array. I am trying to sort by "itemCommodity". I need to sort by numbers only first and then numbers with letters last. For example:

1000 A120 B330 2020年 J954 5000

1000 A120 B330 2020 J954 5000

应显示为:

1000 2020年 5000 A120 B330 J954

1000 2020 5000 A120 B330 J954

我希望有人可以帮助我解决这个问题.我在下面尝试了一个示例,但无法正常工作.

I hope someone can help me out with this. I have an example of what i was trying below but it does not work as expected.

var product_data = [{
"itemCommodity": "1000",
},
{
"itemCommodity": "B330",
},
{
"itemCommodity": "A120",
},
{
"itemCommodity": "J954",
},
{
"itemCommodity": "5000",
},
{
"itemCommodity": "2020",
}]

 product_data.sort(function(a, b) {
     return a.itemCommodity - b.itemCommodity;
 });

请注意,itemCommodity不是数组中唯一的对象.我大约有40个不同的对象,只是尝试对itemCommodity进行排序.

Please note that itemCommodity is not the only object in the array. I have about 40 different objects, just trying to sort on itemCommodity.

推荐答案

您可以尝试像这样比较它们

You can try to compare them like this

product_data.sort(function(a, b) {
     return a.itemCommodity > b.itemCommodity;
});

如果您希望对字母的顺序进行排序,则可以尝试

And if you want the order of the letters to be sorted then you can try this

 product_data.sort(function(a, b) {
     return a.itemCommodity.toLowerCase() > b.itemCommodity.toLowerCase();
});

这篇关于尝试先按数字对数组进行排序,然后按字母对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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