jQuery:根据2个分隔符之间的值对对象数组进行排序

时间:2020-04-11 09:39:46

标签: jquery arrays sorting javascript-objects

是否可以根据两列对对象数组进行排序,但仅考虑2个分隔符之间的值?

例如,我想按大小降序排序,然后按表面降序排序,但仅考虑“-”和“-”之间的值。

就像我有一样

array=[
    {surface: "200", size: "Medium"},
    {surface: "200", size: "Small"},
    {surface: "100", size: "Big"},
    {surface: "300", size: "Medium"},
]

排序为:

array=[
    {surface: "500", size: "Small"},
    {surface: "300", size: "Medium"},
    {surface: "200", size: "Medium"},
    {surface: "100", size: "Big"}

]

但是使用此数组:

array=[
    {surface: "9809-200-45450", size: "fghddffz-Medium-yuifgghj"},
    {surface: "1212-200-43483", size: "sdfsfsdf-Small-fgdfgd"},
    {surface: "2323-100-43264", size: "gdfgsdfg-Big-sddfgdfg"},
    {surface: "9809-300-45450", size: "qdfgqdfg-Medium-hjkghj"},
]

将其排序如下:

array=[
    {surface: "1212-500-43483", size: "sdfsfsdf-Small-fgdfgd"},
    {surface: "9809-300-45450", size: "qdfgqdfg-Medium-hjkghj"},
    {surface: "9809-200-45450", size: "fghddffz-Medium-yuifgghj"},
    {surface: "2323-100-43264", size: "gdfgsdfg-Big-sddfgdfg"}
]

使用标准排序,我会这样做:

array.sort(function(a, b){
    if(a.size == b.size){
        return (a.surface < b.surface)  ? 1 : (a.surface  > b.surface ) ? -1 : 0;
    }
    else{
        return (a.size < b.size) ? 1 : -1;
    }
});

但是我不知道如何用“ a / b.surface”或“ a / b.size”仅替换部分值而不是全部值。 我什至不确定这种方式是否可行。

任何朝着正确方向的建议都是很好的。

谢谢。

0 个答案:

没有答案