-4

Pls refer - http://jsfiddle.net/cbe6vxgh/2/

var datax = $("#x").val();
var e = JSON.parse(datax);

Requirement is to sort the JSON data based on the bdate, as given in fiddle. sorting has to be done only in pure javascript.

I thought of forEach loop, and all, but was not able to sort it.

nikhil rao
  • 381
  • 3
  • 6
  • 9
  • 2
    Please include relevant code in the question itself. There are also [code snippets](http://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) which will allow you to keep all the same fiddle-like functionality – rossipedia Feb 04 '15 at 20:04
  • 1
    `e.sort(function (a, b) { return a.bdate < b.bdate; })` – The Paramagnetic Croissant Feb 04 '15 at 20:04
  • http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript – Xotic750 Feb 04 '15 at 20:04
  • What's your question? Where's your data? Put your code *in the question*. Links to external sites tend to go stale. Also, since you are already using jquery, why the "pure" javascript restriction? – Matt Burland Feb 04 '15 at 20:04
  • @TheParamagneticCroissant it's correct that the OP should use `.sort()` but the comparator function must return an integer (negative, positive, or zero). – Pointy Feb 04 '15 at 20:06
  • @Pointy alright, I always forget that it's the sloppy C-style "total ordering required" comparison function… – The Paramagnetic Croissant Feb 04 '15 at 20:22

1 Answers1

0

Try this:

var datax = $("#x").val();
var e = JSON.parse(datax);

function compare(a,b) {
  var da = a.birthday.split("/");
  da = new Date(da[2], da[0]-1, da[1]);
  var db = b.birthday.split("/");
  db = new Date(db[2], db[0]-1, db[1]);
  if (da < db)
     return -1;
  if (da > db)
    return 1;
  return 0;
}

e.sort(compare);
console.log(JSON.stringify(e));

http://jsfiddle.net/cbe6vxgh/8/

imnancysun
  • 612
  • 8
  • 14