按特定字符串顺序对对象的Javascript数组进行排序?
问题描述:
我有以下数据:按特定字符串顺序对对象的Javascript数组进行排序?
,我想知道我怎么能在一个特定的顺序排序这些。
订单需要为:黄色,蓝色,白色,绿色,红色然后在这些颜色中,它会显示最小的数字。
因此,在这种情况下,正确的排序应该是: Y2,Y3,B0,B2,B6,W2,G7,R4
有没有人对如何实现这一目标的任何想法?如果这使得它更容易,我使用underscore.js。
答
这天真地假定所有元素都有一个有效的颜色(或者至少是第一排序与一个无效的色彩元素):
arr.sort((a, b) => {
const colorOrder = ['yellow', 'blue', 'white', 'green', 'red'];
const aColorIndex = colorOrder.indexOf(a.color);
const bColorIndex = colorOrder.indexOf(b.color);
if (aColorIndex === bColorIndex)
return a.card - b.card;
return aColorIndex - bColorIndex;
});
例子:
const sorted = [
{ color: 'yellow', card: '3' },
{ color: 'red', card: '4' },
{ color: 'blue', card: '6' },
{ color: 'white', card: '2' },
{ color: 'blue', card: '2' },
{ color: 'yellow', card: '2' },
{ color: 'blue', card: '0' },
{ color: 'green', card: '7' },
].sort((a, b) => {
const colorOrder = ['yellow', 'blue', 'white', 'green', 'red'];
const aColorIndex = colorOrder.indexOf(a.color);
const bColorIndex = colorOrder.indexOf(b.color);
if (aColorIndex === bColorIndex)
return a.card - b.card;
return aColorIndex - bColorIndex;
});
// Result:
[
{ "color": "yellow", "card": "2" },
{ "color": "yellow", "card": "3" },
{ "color": "blue", "card": "0" },
{ "color": "blue", "card": "2" },
{ "color": "blue", "card": "6" },
{ "color": "white", "card": "2" },
{ "color": "green", "card": "7" },
{ "color": "red", "card": "4" }
]
答
您可以简单地使用Array.prototype.sort
与您的自定义排序逻辑:
var arr = [
{ color: "yellow", card: "3" },
{ color: "red", card: "4" },
{ color: "blue", card: "6" },
{ color: "white", card: "2" },
{ color: "blue", card: "2" },
{ color: "yellow", card: "2" },
{ color: "blue", card: "0" },
{ color: "green", card: "7" }
];
var arrSorted = arr.sort(function(a, b) {
var colorsOrder = ["yellow", "blue", "white", "green", "red"];
function getColorIndex(x) {
return colorsOrder.indexOf(x.color);
}
return (getColorIndex(a) - getColorIndex(b)) || (a.card - b.card);
});
console.log(arrSorted);
你有什么试过的?您所需要的只是使用'Array.prototype.sort'并实现您的自定义比较逻辑 - 只需4或5行代码。 –