-1

I was trying to do,but i was unable to sort it...I want to sort the data and year in the below output... someone help me to solve in nodejs or in javascript.

var dataCollection = [
        {
            "data": {
                "Oct-2020": 483
            }
        },
        {
            "data": {
                "Nov-2020": 5
            }
        },
        {
            "data": {
                "Mar-2020": 8
            }
        },
        {
            "data": {
                "Apr-2020": 4
            }
        },
         
    ]

I need to sort this array based on the month like

[{
        "data": {
            "Mar-2020": 8
        }
    },
    {
        "data": {
              "Apr-2020": 4
        }
    },
    {
        "data": {
            "Oct-2020": 483
        }
    },
    {
        "data": {
             "Nov-2020": 5
        }
    },

]

Thanks in advance

user10145145
  • 33
  • 1
  • 7

1 Answers1

3

You need to take the key of data and get the numerical value for month and sort by the delta of month and year.

var dataCollection = [{ data: { "Oct-2018": 483 } }, { data: { "Nov-2020": 5  } }, { data: { "Mar-2020": 8  } }, { data: { "Apr-2020": 4 } }],
    month = { Jan: 1, Feb: 2, Mar: 3, Apr: 4, Mey: 5, Jun: 6, Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12 };

dataCollection.sort(({ data: a }, { data: b}) => {
    const
        [mA, yA] = Object.keys(a)[0].split('-'),
        [mB, yB] = Object.keys(b)[0].split('-');

    return yA - yB || month[mA] - month[mB];
});

console.log(dataCollection);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392