How To Sort Array By Name Or Date In Javascript?

Suppose you have an array users. You need to sort the array by name or date.
var users = [
  {id: 1, firstName: 'Anup', created_date: Mar 12 2012 10:00:00 AM}, 
  {id: 2, firstName: 'Tom', created_date: Mar 8 2012 08:00:00 AM}
];
To sort the array of objects by created_date
Turn your strings into dates, and then subtract them to get a value that is either negative, positive, or zero.
Example:
 users.sort((a, b) => new Date(b.created_date) - new Date(a.created_date));   
To sort the array of objects by firstName
Suppose you have an array users. You may use users.sort and pass a function that takes two arguments and compare them (comparator).
It should return
• something negative if first argument is less than second (should be placed before the second in resulting array)
• something positive if first argument is greater (should be placed after second one)
• 0 if those two elements are equal.

In our case if two elements are a and b, we want to compare a.firstname and b.firstname. When sorting strings toLowerCase() is very important - capital letters could affect your sort.
Example:
users.sort((a, b) => a.firstName.toLowerCase() !== b.firstName.toLowerCase() ? a.firstName.toLowerCase() < b.firstName.toLowerCase() ? -1 : 1 : 0);
If compared strings contain unicode characters you can use localeCompare function of String class like the following:
users.sort((a, b) => a.firstname.toLowerCase().localeCompare(b.firstname.toLowerCase()));

Comments

Post a Comment

Popular Posts