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
The
sort
function is organizing theusers
array based on their dates of birth (DOB
). Here’s a detail Explaination:Comparison Function:
sort
function compares two users at a time using a function.Date Comparison:
Sorting:
sort
function rearranges the users based on the comparison results.Array.prototype.sort
accepts a callback function with 2 parameters, essentially what it does is it will determine in which order you want thea
andb
will be after sorted.In this case it calls inside the
sort
functiongetDateFromString
to get theNumber
value of the date of botha
andb
and then it doesreturn d1-d2
which means:d2
is bigger thand1
, it will return negative number and will putd2
afterd1
, which resulting ascending sort.Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort