2

I have an array in this format. I need to sort it descending:

   [{
      "9-Sep" : 6
    }, {
      "8-Sep" : 11
    }, {
      "7-Sep" : 4
    }, {
      "6-Sep" : 11
    }, {
      "5-Sep" : 16
    }, {
      "4-Sep" : 14
    }, {
      "3-Sep" : 3
    }, {
      "2-Sep" : 11
    }, {
      "15-Sep" : 28
    }, {
      "14-Sep" : 6
    }, {
      "13-Sep" : 8
    }, {
      "12-Sep" : 15
    }, {
      "11-Sep" : 24
    }, {
      "10-Sep" : 19
    }];

I am using this function but it is sorting only if values are not there.

function myname() {
    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
        };

    json.sort(function (a,b) {
        var as = a.split('-'),
            bs = b.split('-');

        ad.setDate(as[0]);
        ad.setMonth(months[as[1]]);
        bd.setDate(bs[0]);
        bd.setMonth(months[bs[1]]);

        return ad - bd;
    });
};

How to sort the above array with values?

5
  • 1
    Please note that the problem has nothing to do with JSON at all. It's rather about how to process arrays/objects in JavaScript. How you obtained the data (e.g. via JSON) is irrelevant to the problem. Commented Sep 17, 2013 at 6:05
  • What does "It is sorting only if values are not there" mean? What values are you talking about? Commented Sep 17, 2013 at 6:06
  • [ { "6-Sep" }, { "5-Sep" }, { "4-Sep" }, { "3-Sep" } ]; If it like this above function is sorting. but If come with values like above json ,then am not able to sort..? Commented Sep 17, 2013 at 6:07
  • 1
    Ah, so it works if you have an array of strings (["9-Sep", "8-Sep", ...]) but not an array of objects ([{"9-Sep" : 6}, {"8-Sep" : 11}, ...]). If you have an array of objects, then a and b will be objects and you'd have to extract the property name first. It might be easier to use an array of arrays instead: [["9-Sep", 6], ["8-Sep", 11], ...]. Commented Sep 17, 2013 at 6:09
  • @FelixKling Yeah u r right.. My collection structure is restricted to the above format. So i did not think out of box.Thanks Commented Sep 17, 2013 at 6:14

2 Answers 2

3

As others have mentioned, you'll probably have to extract your data to a different format to sort it:

var newArray = [];

//Extract array of transformed objects
for(var i = 0; i < json.length; i++) {
    var element = json[i];
    for(var key in element) {
        if(element.hasOwnProperty(key)) {
            newArray.push({ date: key, val: element[key]})
            break;
        }
    }
}

//Sort transformed array
newArray.sort(function(a,b) {
    var as = a.date.split('-'),
        bs = b.date.split('-');

    ad.setDate(as[0]);
    ad.setMonth(months[as[1]]);
    bd.setDate(bs[0]);
    bd.setMonth(months[bs[1]]);

    return ad - bd;
});

//Transform back to old format
for(var i = 0; i < newArray.length; i++) {
    var x = {};
    x[newArray[i].date] = newArray[i].val;
    json[i] = x;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Below code works fine and does what you actually want.

<script>    
     records = [{ "21-Feb": "IndPak" }, { "12-Oct": "AusSA" }, { "9-Sep": "WINZD" }, { "1-Jun": "NZDSL" }];
                    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
                    };

                    records = records.sort(function (d1, d2) {

                        var date1 = new Date(), date2 = new Date()
                        for (var prop in d1) {

                            if (d1.hasOwnProperty(prop)) {
                                day = prop.split("-")[0];
                                month = prop.split("-")[1];

                                date1.setDate(parseInt(day));
                                date1.setMonth(parseInt(months[month]));
                            }
                        }
                        for (var prop in d2) {

                            if (d2.hasOwnProperty(prop)) {
                                day = prop.split("-")[0];
                                month = prop.split("-")[1];

                                date2.setDate(parseInt(day));
                                date2.setMonth(parseInt(months[month]));
                            }
                        }

                        return date1 - date2; // Ascending
                        //return date2 - date1; // Descending
                    });

    </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.