我想就这个小问题得到您的帮助。
我想根据 代码 值 而不是字母顺序 对数组 进行排序。 ( 我用粗体字指定了该名称,但最终还是被标记出来了,人们甚至都不在乎阅读该问题 )
例如,我想有所有 绿色的 对象,那么所有的 蓝色 的人,然后将所有的 红色 的。最好的方法是什么?
[ { 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 函数可以做到这一点吗?在这种情况下会是什么情况?
您可以为所需订单取一个对象。
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; }
对于未知的颜色/值,可以将默认值与
0
Infinity
最后,您可以使用逻辑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; }