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

标签 javascript sorting underscore.js

我有以下数据:

enter image description here

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

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

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

关于javascript - 按特定字符串顺序对对象的 Javascript 数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38966514/

相关文章:

javascript - 根据 slider 滑翔机 js 中的事件 li 值更改 css 值

javascript - 多个 div 淡入/淡出滚动效果不起作用

sorting - 按(任意)字段名称对结构数组进行简单排序的最短方法是什么?

javascript - 单击时按钮不调用函数

javascript - 下划线模板在 IE 8 中失败并显示 "unexpected identifier"

javascript - 如果元素是由指令生成的,ng-click 不起作用

javascript - 在这种情况下,如何使用 get、set 和 toggle 函数重构 v-model?

c++ - 如何在 C++ 中打印案例的运行时间

sql - MySQL中的条件排序?

arrays - 按值对嵌套数组进行排序?