按特定的字符串顺序对对象的Javascript数组排序?
问题描述:
我有以下数据:
我想知道如何按特定顺序对它们进行排序.
and I was wondering how I could sort these in a specific order.
顺序必须为:黄色,蓝色,白色,绿色,红色,然后在这些颜色内,它将首先显示最小的数字.
The order needs to be: Yellow, Blue, White, Green, Red and then within those colors, it would show the smallest number first.
因此,在这种情况下,正确的排序应为: y2,y3,b0,b2,b6,w2,g7,r4
So in this case, the correct sorting should be: y2, y3, b0, b2, b6, w2, g7, r4
有人对如何实现这一目标有任何想法吗?我正在使用underscore.js,如果这样做更容易.
Does anyone have any ideas on how to accomplish that? I'm using underscore.js if that makes it easier.
答
这天真地假设所有元素都具有有效的颜色(或者至少它首先对具有无效颜色的元素进行排序):
This naively assumes that all elements have a valid color (or at least it sorts elements with an invalid color first):
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" }
]