0
months = ['Apr','Jan','Jul','Jun']
values = ['2','4','10','1']

How do I sort them not alphabetically but customized like below so the sorted arrays should be:

sMonths = ['Jan','Apr','Jun','Jul']
sValues = ['4','2','1','10']

I am guessing it should be done by map method? I checked here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

But I couldn't really understand how to do it.

2 Answers 2

2

Combine months and values into one array, sort it, and then extract months and values back.

allMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

months = ['Apr','Jan','Nov','Jun']
values = ['2','4','10','1']

combined = months.map(function(m, i) {
  return [allMonths.indexOf(m), m, values[i]];
}).sort(function(x, y) {
  return x[0] - y[0]
});

sMonths = combined.map(function(x) { return x[1] });
sValues = combined.map(function(x) { return x[2] });

document.write(JSON.stringify(sMonths) + "<br>");
document.write(JSON.stringify(sValues) + "<br>");

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, this was the type of an answer I was looking for!
nicely done. I was confused at the question but the answer cleared the question for me.
This is not going to work in all cases, say you will sort "Nov" before "Apr". This is because you are trying to sort combined, which is an array of array. The way sort does it is to do a toString() on each of the sub-arrays and sort them as strings. You have to write a custom sort function to make it work.
@AlanTam Thank you so much, I was getting this bug and trying to figure out why it was happening!
-1

you should better store month as id (1->12) and at the end translate them into month names, but Andy E response fill your needs on Sort day/month array in Javascript

(function () { 
    // Set up our variables, 2 date objects and a map of month names/numbers
    var ad = new Date(),
        bd = new Date(),
        months = {
            Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5,
            Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov:10, Dec:12
        };

    MyArray.sort(function (a,b) {
        // Split the text into [ date, month ]
        var as = a.split(' '),
            bs = b.split(' ');

        // Set the Date() objects to the dates of the items
        ad.setDate(as[0]);
        ad.setMonth(months[as[1]]);
        bd.setDate(bs[0]);
        bd.setMonth(months[bs[1]]);

        /* A math operation converts a Date object to a number, so 
           it's enough to just return date1 - date2 */
        return ad - bd;
    });
})();
//-> ["09 Jun", "13 Jun", "30 Jun", "13 Aug", "25 Aug"]

1 Comment

Would do, but I will wait for a better way and thank you for the example code snippet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.