skip to Main Content

I have a JavaScript multidimensional array:

var people = [
    { id: 1, name: "Hannah", birthdate: "04/16/2002" },
    { id: 2, name: "Sofia",  birthdate: "03/18/2012" },
    { id: 3, name: "Robert", birthdate: "12/22/1997" },
];

How can I sort them by their birthday date?

2

Answers


  1. you sort a birthday date value like:

    people.sort(function(a, b) {
      var dateA = new Date(a.birthdate);
      var dateB = new Date(b.birthdate);
      return dateA - dateB;
    });
    Login or Signup to reply.
  2. Using array sort method

    DOCS HERE

    var people = [
        { id: 1, name: "Hannah", birthdate: "04/16/2002"},
        { id: 2, name:"Sofia", birthdate: "03/18/2012" },
        { id: 3, name:"Robert", birthdate: "12/22/1997" },
      { id: 4, name:"Robert", birthdate: "12/22/2005" },
      { id: 5, name:"Robert", birthdate: "12/22/2015" },
    ];
    
    const res = people.sort((a,b)=> new Date(a.birthdate) - new Date(b.birthdate));
    
    console.log(res)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search