您可以为所需订单取一个对象。
var array = [{ pre: "RED", value: 0 }, { pre: "BLUE", value: 0 }, { pre: "RED", value: 0 }, { pre: "GREEN", value: 0 }, { pre: "BLUE", value: 0 }, { pre: "RED", value: 0 }, { pre: "GREEN", value: 0 }, { pre: "BLUE", value: 0 }], order = { GREEN: 1, BLUE: 2, RED: 3 };array.sort(function (a, b) { return order[a.pre] - order[b.pre];});console.log(array);.as-console-wrapper { max-height: 100% !important; top: 0; }对于未知的颜色/值,可以将默认值与
0
,用于排序到顶部或Infinity
为了排序到最后,- 或用于在其他组之间进行排序的任何其他值。
最后,您可以使用逻辑OR
||链接的其他排序部分对特殊处理的项目进行排序。
var array = [{ pre: "YELLOW", value: 0 }, { pre: "BLACK", value: 0 }, { pre: "RED", value: 0 }, { pre: "BLUE", value: 0 }, { pre: "RED", value: 0 }, { pre: "GREEN", value: 0 }, { pre: "BLUE", value: 0 }, { pre: "RED", value: 0 }, { pre: "GREEN", value: 0 }, { pre: "BLUE", value: 0 }], order = { GREEN: 1, BLUE: 2, RED: 3, default: Infinity };array.sort(function (a, b) { return (order[a.pre] || order.default) - (order[b.pre] || order.default) || a.pre.localeCompare(b.pre);});console.log(array);.as-console-wrapper { max-height: 100% !important; top: 0; }


