按特定字符串顺序对Javascript对象数组进行排序?

时间:2016-08-16 04:08:18

标签: javascript sorting underscore.js

我有以下数据:

enter image description here

我想知道如何按特定顺序对这些进行排序。

订单必须是:黄色,蓝色,白色,绿色,红色,然后在这些颜色中,它将首先显示最小的数字。

所以在这种情况下,正确的排序应该是: y2,y3,b0,b2,b6,w2,g7,r4

有没有人对如何实现这一点有任何想法?我使用underscore.js,如果这样可以更容易。

1 个答案:

答案 0 :(得分:9)

这天真地假设所有元素都有一个有效的颜色(或者至少它首先对无效颜色的元素进行排序):

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" }
]