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

Sorting Javascript array of objects by specific string order?

我有以下数据:

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

顺序需要是:黄色、蓝色、白色、绿色、红色然后在这些颜色中,它会先显示最小的数字。

所以在这种情况下,正确的排序应该是: 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);