Created
June 1, 2016 14:26
-
-
Save karlhorky/2dd1b69688b81c2881f956276e1d10a5 to your computer and use it in GitHub Desktop.
JavaScript: Produce new array from .reduce(), with map- and filter-like transformation in one step.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Produce new array from .reduce(), with map- and filter-like transformation in one step. | |
// Example data courtesy of http://elijahmanor.com/reducing-filter-and-map-down-to-reduce/ | |
const doctors = [ | |
{ number: 1, actor: "William Hartnell", begin: 1963, end: 1966 }, | |
{ number: 2, actor: "Patrick Troughton", begin: 1966, end: 1969 }, | |
{ number: 3, actor: "Jon Pertwee", begin: 1970, end: 1974 }, | |
{ number: 4, actor: "Tom Baker", begin: 1974, end: 1981 }, | |
{ number: 5, actor: "Peter Davison", begin: 1982, end: 1984 }, | |
{ number: 6, actor: "Colin Baker", begin: 1984, end: 1986 }, | |
{ number: 7, actor: "Sylvester McCoy", begin: 1987, end: 1989 }, | |
{ number: 8, actor: "Paul McGann", begin: 1996, end: 1996 }, | |
{ number: 9, actor: "Christopher Eccleston", begin: 2005, end: 2005 }, | |
{ number: 10, actor: "David Tennant", begin: 2005, end: 2010 }, | |
{ number: 11, actor: "Matt Smith", begin: 2010, end: 2013 }, | |
{ number: 12, actor: "Peter Capaldi", begin: 2013, end: 2013 } | |
]; | |
// As in the link about combining JS arrays below, we can use .concat() to return a new array. | |
// https://davidwalsh.name/combining-js-arrays#concat | |
const newDoctors = doctors.reduce((memo, doctor) => | |
doctor.begin > 2000 ? // this serves as our `filter` | |
memo.concat({ // this serves as our `map` | |
doctorNumber: "#" + doctor.number, | |
playedBy: doctor.actor, | |
yearsPlayed: doctor.end - doctor.begin + 1 | |
}) : memo | |
, []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment