Skip to content

Instantly share code, notes, and snippets.

@neuralline
Created May 1, 2020 15:43
Show Gist options
  • Save neuralline/e33a55df96187bb3e16d15a19de1b6d9 to your computer and use it in GitHub Desktop.
Save neuralline/e33a55df96187bb3e16d15a19de1b6d9 to your computer and use it in GitHub Desktop.
ES6 Filter, Sort, Map method chaining
/* PRINT OUT TO THE CONSOLE,
AN ORDERED LIST OF "ACTIVE" USERS,
BY ASENDING SURNAME (ie A, B, C),
WITH A STRING SHOWING USERS FULL NAME AND AGE TO WHOLE NUMBER
ie
"Jerry Brie is 80 years old."
"Mickey Jacobs is 92 years old."
"Tom Oswalt is 80 years old."
*/
const USERS = [
{ name: "Troy Barnes", dob: "1989-12-04", active: false },
{ name: "Abed Nadir", dob: "1979-03-24", active: true },
{ name: "Jeff Winger", dob: "1974-11-20", active: true },
{ name: "Pierce Hawthorne", dob: "1944-11-27", active: false },
{ name: "Annie Edison", dob: "1990-12-19", active: true },
{ name: "Britta Perry", dob: "1980-10-19", active: true },
{ name: "Shirley Bennett", dob: "1971-08-12", active: false },
{ name: "Professor Professorson", dob: "1969-03-27", active: false },
{ name: "Craig Pelton", dob: "1971-07-15", active: true },
];
//calculate age from dob
const getAge = (birthDate) =>
Math.floor((new Date() - new Date(birthDate).getTime()) / 3.15576e10);
/**
*
* Chained methods= [
* filter active users,
* then sort users by their las name,
* then console log result
* ]
*
*/
const sortActiveUsersByLastName = (users) => {
users
.filter((user) => user.active === true)
.sort((a, b) => (a.name.split(" ")[1] > b.name.split(" ")[1] ? 1 : -1))
.map((user) => {
const dob = getAge(user.dob);
console.log(`${user.name} is ${dob} years old `);
});
};
//call the function
sortActiveUsersByLastName(USERS);
/**
* Should output,
* Annie Edison is 29 years old,
* Abed Nadir is 41 years old,
* Craig Pelton is 48 years old,
* Britta Perry is 39 years old,
* Jeff Winger is 45 years old,
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment