Quick Tech Tip – How to use the Array.prototype.map() JavaScript method

The Array.prototype.map() method takes in an array and creates and returns a new array with the results.

Let’s take a look at an example…

Here’s an array of scientist data with first name, last name, date of birth and date of passing on:

const scientists = [
{ first: ‘Isaac’, last: ‘Newton’, year: 1643, passed: 1727 },
{ first: ‘Galileo’, last: ‘Galilei’, year: 1564, passed: 1642 },
{ first: ‘Marie’, last: ‘Curie’, year: 1867, passed: 1934 },
{ first: ‘Johannes’, last: ‘Kepler’, year: 1571, passed: 1630 },
{ first: ‘Nicolaus’, last: ‘Copernicus’, year: 1473, passed: 1543 },
{ first: ‘Max’, last: ‘Planck’, year: 1858, passed: 1947 },
{ first: ‘Sarah E.’, last: ‘Goode’, year: 1855, passed: 1905 },
{ first: ‘Lise’, last: ‘Meitner’, year: 1878, passed: 1968 },
{ first: ‘Albert’, last: ‘Einstein’, year: 1879, passed: 1955 },
];
We can use the map() method on the original scientists array and return a new array from the list of last name and date of birth:
const firstDOB = scientists.map(scientist => scientist.first + scientist.passed);
console.table(firstDOB);
Finally, we console log the concatenated result to the console with console.table;
Array map() method - London Developement

That concludes today’s quick tech time.