Dre*_*rew 0 javascript sorting underscore.js
我有以下数据:
我想知道如何按特定顺序对这些进行排序.
订单需要是:黄色,蓝色,白色,绿色,红色,然后在这些颜色中,它将首先显示最小的数字.
所以在这种情况下,正确的排序应该是: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;
} );
Run Code Online (Sandbox Code Playgroud)
例:
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" }
]
Run Code Online (Sandbox Code Playgroud)