πŸ—ΎMap Helper

The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.

Use Case - 1: In the following example, each number in an array is doubled.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled);
Output :
[ 2, 4, 6, 8 ]

Use Case - 2: Traversing an existing array value.

const tasks = [
  {
    'name'     : 'Write for Envato Tuts+',
    'duration' : 120
  },
  {
    'name'     : 'Work out',
    'duration' : 60
  },
  {
    'name'     : 'Procrastinate on Duolingo',
    'duration' : 240
  }
];
const task_names = tasks.map(task => task.name)
console.log(task_names)
Output :
[ 'Write for Envato Tuts+', 'Work out', 'Procrastinate on Duolingo' ]

Use Case - 3: Traversing an existing array value.

let peoples = [
  { firstName: "Macom", lastName: "Reynolds" },
  { firstName: "Kaylee", lastName: "Frye" },
  { firstName: "Jayne", lastName: "Cobb" },
];

const results = peoples.map((person) => {
  return [person.firstName, person.lastName];
});

console.log(results);
Output :
[ [ 'Macom', 'Reynolds' ], [ 'Kaylee', 'Frye' ], [ 'Jayne', 'Cobb' ] ]]

Last updated