按特定的字符串顺序对对象的Javascript数组排序? [英] Sorting Javascript array of objects by specific string order?

查看:158
本文介绍了按特定的字符串顺序对对象的Javascript数组排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

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

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.

因此,在这种情况下,正确的排序应为: y2,y3,b0,b2,b6,w2,g7,r4

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

有人对如何实现这一目标有任何想法吗?我正在使用underscore.js,如果这样做更容易.

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

推荐答案

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

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

示例:

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数组排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆