skip to Main Content

there is an array called users which has objects with in there is personal information of different persons.
there is a function called getDatesfromString which strips string to date format.
there is a variable called sorted_user which is meant to contain the sorted user array.
the thing i don’t understand is that how sort function sorts the user by getting their Date of birth , I need detail explanation?

let users = [
    {
        firstName: "John",
        lastName: "wick",
        email:"[email protected]",
        DOB:"22-01-1990",
    },
    {
        firstName: "John",
        lastName: "smith",
        email:"[email protected]",
        DOB:"21-07-1983",
    },
    {
        firstName: "Joyal",
        lastName: "white",
        email:"[email protected]",
        DOB:"21-03-1989",
    },
];

function getDateFromString(strDate) {
    let [dd,mm,yyyy] = strDate.split('-')
    return new Date(yyyy+"/"+mm+"/"+dd);
}
    
// console.log(sorted_users);
    let sorted_users=users.sort(function(a, b) {
        let d1 = getDateFromString(a.DOB);
        let d2 = getDateFromString(b.DOB);
            return d1-d2;
          });
    console.log(sorted_users);

2

Answers


  1. The sort function is organizing the users array based on their dates of birth (DOB). Here’s a detail Explaination:

    1. Comparison Function:

      • The sort function compares two users at a time using a function.
      • This function converts the birthdate strings to date objects for accurate comparison.
    2. Date Comparison:

      • For each pair of users, it subtracts one birthdate from the other.
      • If the result is negative, it means the first user is born earlier.
      • If positive, the first user is born later.
      • If zero, their order remains unchanged.
    3. Sorting:

      • The sort function rearranges the users based on the comparison results.
      • After sorting, the array is in ascending order of birthdates.
    Login or Signup to reply.
  2. Array.prototype.sort accepts a callback function with 2 parameters, essentially what it does is it will determine in which order you want the a and b will be after sorted.

    In this case it calls inside the sort function getDateFromString to get the Number value of the date of both a and b and then it does return d1-d2 which means:

    • if d2 is bigger than d1, it will return negative number and will put d2 after d1, which resulting ascending sort.
    compareFn(a, b) return value sort order
    > 0 sort a after b, e.g. [b, a]
    < 0 sort a before b, e.g. [a, b]
    === 0 keep original order of a and b

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search