Map & Reduce Array Elements in JavaScript

JavaScript·2 min read·Jan 1, 2025

In JavaScript, arrays come with a few built-in methods for transforming their elements.

Transform array elements

To transform the elements of an array and replace their current value with a new one, you can use the map() method of the array instance:

array.map((element, index) => {  return value;});

Where:

  • element is the current element.
  • index is the index of the current element in the array.
  • value is the new value of the current element.

This method loops on each element of the array and replaces the value of the current element with the one returned by the callback function.

Note: If the callback function doesn't return a value, the value of the current element will be automatically replaced with undefined.

Example

Let's consider this script, that selectively adds a new property to the objects of an array:

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.