Sort array of objects by quarterly-yearly data in JavaScript -


i have array of data containing objects below

[      {         "name":"q1'2016",       "y":0    },    {         "name":"q2'2016",       "y":0    },    {         "name":"q3'2016",       "y":0    },    {         "name":"q4'2015",       "y":0    } ] 

i want sort them based on quarterly, q4'2015 should come first, q1'2016 , on.

how can acheived?

you can use sort method , give callback sort object based on predicate; in case, want inspect objects' name property containing quarter-year information. since you'll have data different quarters , years, you'll want map quarters month values can convert them year/month dates , compare them way.

var data = [{    "name": "q1'2016",    "y": 0  }, {    "name": "q2'2016",    "y": 0  }, {    "name": "q3'2016",    "y": 0  }, {    "name": "q4'2015",    "y": 0  }];    var quartertomonthmap = {    "q1": 0,    "q2": 3,    "q3": 6,    "q4": 9  }    function sortbyquarteryear(lhs, rhs) {    var lhsquarteryear = lhs.name.split("'");    var rhsquarteryear = rhs.name.split("'");    var lhsdate = new date(lhsquarteryear[1], quartertomonthmap[lhsquarteryear[0]]);    var rhsdate = new date(rhsquarteryear[1], quartertomonthmap[rhsquarteryear[0]]);    return lhsdate.gettime() - rhsdate.gettime();  }    document.write(json.stringify(data.sort(sortbyquarteryear)));


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -