按属性对对象数组进行排序(使用自定义顺序,而不是按字母顺序) [英] Sort an array of object by a property (with custom order, not alphabetically)

查看:103
本文介绍了按属性对对象数组进行排序(使用自定义顺序,而不是按字母顺序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想得到你对这个小问题的帮助。

I would like to get your help about this little problem.

我想订购这个数组,具体取决于代码但不是按字母顺序排列。
我用粗体指定了这个,但最终还是被标记了,人们甚至不关心阅读问题

I have like to order this array depending on the code value but not in alphabetical order. (I specified this in bold but got eventually flagged anyway, people don't even care about reading the question)

例如,我希望拥有所有绿色对象,然后是所有蓝色对象,然后是所有红色的。最好的方法是什么?

For example I would like to have all the green objects, then all the blue ones and then all the red ones. What is the best way to do that?

[
    { code: "RED", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0}
]

是否可以做使用 sort 函数?在这种情况下条件是什么?

Is it possible to do that with the sort function? What would the condition be in that case?

推荐答案

您可以为所需订单获取一个对象。

You could take an object for the wanted order.

var array = [{ code: "RED", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }],
    order = { GREEN: 1, BLUE: 2, RED: 3 };
    
array.sort(function (a, b) {
    return order[a.code] - order[b.code];
});

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }

对于未知颜色/值,您可以使用默认值with

For unknow colors/values, you could use a default value with


  • 0 ,排序到顶部或

  • Infinity 用于排序到最后,

  • 或用于在其他组之间进行排序的任何其他值。

  • 0, for sorting to top or
  • Infinity for sorting to the end,
  • or any other value for sorting inbetween the other groups.

最后,您可以使用其他排序部件对特殊处理物品进行排序,并使用逻辑OR ||

At last you could sort the special treated items with an other sorting part, chained with logical OR ||.

var array = [{ code: "YELLOW", value: 0 }, { code: "BLACK", value: 0 }, { code: "RED", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }],
    order = { GREEN: 1, BLUE: 2, RED: 3, default: Infinity };
    
array.sort(function (a, b) {
    return (order[a.code] || order.default) - (order[b.code] || order.default) || a.code.localeCompare(b.code);
});

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于按属性对对象数组进行排序(使用自定义顺序,而不是按字母顺序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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