Sorting Javascript array of objects by specific string order?

风格不统一 提交于 2020-06-27 05:56:13

问题


I have the following data:

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.

So in this case, the correct sorting should be: y2, y3, b0, b2, b6, w2, g7, r4

Does anyone have any ideas on how to accomplish that? I'm using underscore.js if that makes it easier.


回答1:


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;
} );

Example:

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



回答2:


You can simply use Array.prototype.sort with your custom sorting logics:

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);


来源:https://stackoverflow.com/questions/38966514/sorting-javascript-array-of-objects-by-specific-string-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!