Home/Blog/Programming/JavaScript array methods: How to use the map and reduce
Home/Blog/Programming/JavaScript array methods: How to use the map and reduce

JavaScript array methods: How to use the map and reduce

8 min read
May 15, 2025
content
Arrays in JS
What are array properties?
What are array methods?
Array map() method
More examples on the map() method
Using map() to convert a string to an ASCII byte array
Mapping an array of numbers to an array of their square roots
Mapping an array of numbers with a function containing an argument
Array reduce() method
More examples of the reduce() method
Sum the values of an array
Flatten an array of arrays
Group objects by a property
Using reduce() and map() together
Conclusion

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Key takeaways:

  • The map() method applies a function to each array element, creating a new array with the returned values. It’s ideal for tasks like transforming data, calculating square roots, or generating ASCII values.

  • The reduce() method processes an array to produce a single cumulative value. Common applications include summing array values, flattening nested arrays, or grouping objects by properties.

  • JavaScript array methods like map() and reduce() enhance data management by allowing developers to modify, query, and organize arrays efficiently without altering the original data structure.

  • These methods can simplify complex operations, such as counting array elements that satisfy specific conditions or aggregating data in multi-dimensional arrays.

Ever struggled with transforming or summarizing data in JavaScript? Loops can be tedious, and writing custom functions for every transformation feels inefficient. That’s where JavaScript’s built-in array methods—map() and reduce()—come in. These two methods streamline data manipulation, making our code more readable and concise. This blog will discuss how to use them effectively with practical examples.

Let’s dive in!

Arrays in JS#

In JavaScript, arrays are ordered collections of values accessible via numerical indexes. Unlike objects, which use named keys, arrays simplify data storage when order matters. They are flexible, allowing dynamic resizing and built-in methods for efficient data manipulation.

Understanding JavaScript arrays: Indexing and structure
Understanding JavaScript arrays: Indexing and structure

Arrays are easy to declare in JavaScript. Below, we create an array of fruit types and store them orderly.

var fruit = [
  "Apple",
  "Banana",
  "Kiwi",
  "Orange"
];

Arrays in JavaScript have special features that make them particularly useful, including:

  • They are dynamic.
  • They can be sparse or dense.
  • They are mutable.
  • They have methods and properties to make the organization convenient.
Array of fruits
Array of fruits

If you are a beginner and want to learn about JavaScript, check out the Educative’s course below. It will start from the basics of JavaScript and lead you to mastery.

Learn JavaScript

Cover
Learn to Code: Javascript for Absolute Beginners

JavaScript is a versatile language essential for web development, working alongside HTML and CSS to build both simple and complex web applications. This course offers a comprehensive introduction to JavaScript for beginners, starting with fundamental concepts like problem-solving and simple JavaScript programs. Through interactive exercises, challenges, and quizzes, learners will master control structures, loops, strings, arrays, and functions. By the end of this course, you'll have solid problem-solving skills, a deep understanding of JavaScript programming, and practical experience in writing clean, efficient code. This knowledge will prepare you for a successful career as a JavaScript developer and significantly enhance your employability in the tech industry.

8hrs
Beginner
4 Challenges
4 Quizzes

What are array properties?#

Array properties define specific attributes of an array, such as its size or structure. These are usually static values that describe or affect the array’s behavior. For example:

  • length: Returns the number of elements in the array.

  • prototype: Provides shared methods and properties for all array instances.

Properties allow you to query or adjust key characteristics of an array without extra effort.

What are array methods?#

Array methods, conversely, are actions or functions that you can apply to an array to manipulate data. For example:

  • push(): Adds one or more elements to the end of the array.

  • pop(): Removes the last element from the array.

These methods simplify modifying, accessing, and organizing array data dynamically.

Functions are a set of instructions that carry out a task. They allow us to reuse code anywhere in the program.

Why does it matter?

With these tools, you don’t need to create custom objects or write repetitive code. Array methods and properties provide a robust framework for handling data efficiently.

Now, we’ll examine two powerful JavaScript array methods—map() and reduce()—and see how they simplify common data operations.

Array map() method#

The map() method creates a modified version of an array by applying a callback function to each element. It returns a new array containing the results of the function applied to every element in the original array without altering the original array.

The syntax of the method is as follows:

array.map(function(currentValue, index, arr), thisValue)

The map() method accepts two parameters:

  • function(currentValue, index, arr): This parameter is required to run on each array element. It contains three parameters: currentValue, index, and arr.

  • thisValue: This optional parameter represents the value to be used as this when executing the callback function. If not provided, undefined is used as the default value.

The map() method applies a callback function to each element of an array and returns a new array with the results. The function passed to map() receives arguments in the following order:

function callbackfn(value: any, index: number, array: any[])

For each element, the callbackfn will be passed with its value as the first argument, its index as the second argument, and the array as the third argument. This callbackfn function takes between 0 and 3 arguments.

Finally, the map method returns a new array with all the returned values from the callbackfn function. Check out an example below:

Javascript (babel-node)
var arr = [10, 20, 30, 40, 50]; // initialize an array and assign it to arr
var arr1 = arr.map(a => a * 2); // double the element in the array
console.log("arr:",arr); // print original array
console.log("doubled array:",arr1); // print doubled array

Note: You can see that the map() method maps the arrow function to each element and returns a new array. The original array remains unchanged.

More examples on the map() method#

There are many uses of map() in your JavaScript code. Let’s break down the most common ones.

Using map() to convert a string to an ASCII byte array#

Below, our code shows how to use this method on a String to generate an array of bytes in ASCII encoding.

Javascript (babel-node)
// Assign the map() method from Array.prototype to a variable
let map = Array.prototype.map;
/**
* Use map.call() to apply the map() method to a string
* JavaScript treats strings as array-like, allowing us to use map() on them
* Each character is mapped to its ASCII (char code) value
*/
let a = map.call('Hello World', function (x) {
return x.charCodeAt(0); // Convert each character to its ASCII value
});
// Print the array of ASCII values
console.log(a);
Mapping an array of numbers to an array of their square roots#

Below, our code takes an array of numbers and creates a new array with the square roots of each number.

Javascript (babel-node)
// Initialize an array of numbers
let numbers = [3, 25, 100];
/**
* Use the map() method to create a new array
* where each number is replaced by its square root
*/
let roots = numbers.map(function(num) {
return Math.sqrt(num); // Calculate the square root of each element
});
// Print the new array containing square roots
console.log(roots);
Mapping an array of numbers with a function containing an argument#

Below, our code shows how map() can be used alongside a function with one argument. The argument will be assigned automatically from each element of the array.

Javascript (babel-node)
// Initialize an array of numbers
let numbers = [3, 25, 100];
/**
* Use the map() method to create a new array
* where each number is doubled
*/
let doubles = numbers.map(function(num) {
return num * 2; // Multiply each element by 2
});
// Print the new array with doubled values
console.log(doubles);

Tips: As map() builds a new array, you should not use this method if:

  • You are not using the array that is returned.

  • You are not returning any value from the callback.

Array reduce() method#

The reduce() method reduces the array to a single value from left to right. This method leaves the original array unchanged.

The syntax of the method is as follows:

arr.reduce(<function>);

The reduce() method iterates through an array, applying a function to each element and accumulating a single result. It takes the return value from the previous iteration and uses it as input for the next, progressively combining all elements into a final value. The method passes arguments to the callback function in the following order:

function callbackfn(prev: any, curr: any, index: number, array: number[])

For each element, the callbackfn will be passed with the previous callbackfn function’s return value as the first argument and the element’s value as the second argument. This is followed by the index of the element as the third argument. Lastly, the array itself is taken as the fourth argument.

The callbackfn function returns a value that becomes the accumulator for the next iteration. If the array has only one value, that value is returned. For an empty array, an error is thrown.

Let’s learn more about reduce with an example below:

Javascript (babel-node)
var arr = [10, 20, 30, 40, 50]; // Initialize an array and assign it to arr
var val = arr.reduce((prev, curr) => prev + curr); // Reduce element to sum
console.log("arr:",arr); // Print original array
console.log("reduced val:",val); // Print element returned by reduce

Here, the arrow function takes the previous value prev and adds it to the value iterated in the array curr. The reduce method sums up the entire array.

Note: We can use the reduceRight method to apply the reduce method in the opposite direction.

More examples of the reduce() method#

There are many uses of reduce in your JavaScript code. Let’s break down the most common ones.

Sum the values of an array#

We can use reduce to sum all the values of an array in an easy way.

Javascript (babel-node)
// Initialize an array with values
var arr = [10, 20, 30, 40, 50];
// Use reduce() to sum all elements in the array (left to right)
var sum = arr.reduce((prev, curr) => prev + curr, 0);
// Print the original array
console.log("Original Array:", arr);
// Print the reduced value (sum of array elements)
console.log("Sum using reduce():", sum);
// Use reduceRight() to sum all elements in the array (right to left)
var sumRight = arr.reduceRight((prev, curr) => prev + curr, 0);
// Print the reduced value using reduceRight()
console.log("Sum using reduceRight():", sumRight);

Flatten an array of arrays#

The below code uses the reduce() method to flatten a nested array into a single-level array:

Javascript (babel-node)
// Initialize a nested array
var nestedArray = [[0, 1], [2, 3], [4, 5]];
// Use reduce() to flatten the array from left to right
var flattened = nestedArray.reduce((prev, curr) => prev.concat(curr), []);
// Print the original nested array
console.log("Nested Array:", nestedArray);
// Print the flattened array
console.log("Flattened Array (Left to Right):", flattened);
// Use reduceRight() to flatten the array from right to left
var flattenedRight = nestedArray.reduceRight((prev, curr) => prev.concat(curr), []);
// Print the flattened array using reduceRight()
console.log("Flattened Array (Right to Left):", flattenedRight);

Group objects by a property#

The code below groups an array of objects by a specified property (age) using the reduce() method to create an object where keys represent property values and values are arrays of corresponding objects.

Javascript (babel-node)
// Initialize an array of people objects with name and age properties
let people = [
{ name: 'Matt', age: 25 },
{ name: 'Asma', age: 23 },
{ name: 'Cami', age: 29 }
];
/**
* Function to group objects in an array based on a specified property
* @param {Array} objectArray - The array of objects to group
* @param {string} property - The property to group objects by
* @returns {Object} - An object where keys are unique property values, and values are arrays of matching objects
*/
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
let key = obj[property]; // Extract the property value for grouping
if (!acc[key]) { // If key doesn't exist in accumulator, initialize an empty array
acc[key] = [];
}
acc[key].push(obj); // Push the current object into the corresponding array
return acc;
}, {}); // Initialize accumulator as an empty object
}
// Group the people array by the 'age' property
let groupedPeople = groupBy(people, 'age');
// Print the grouped result
console.log(groupedPeople);

Using reduce() and map() together#

Now, let’s learn an example of how we can use the two methods together to make certain tasks easier. Often, we need to count array elements that satisfy a certain condition. Here’s how it’s done:

  1. Map the array into an array of zeros and ones.
  2. Reduce the array of zeros and ones into the sum.

The final output is a count of elements that satisfy a given condition.

Javascript (babel-node)
var arr = ['Hello', 1, true, NaN, 'Bye']; // Initialize an array of elements
var countArr = arr.map(ele => typeof ele === 'string' ? 1 : 0); // map to 0 and 1
var sum = countArr.reduce((prev, curr)=> prev + curr); // reduce for sum
console.log("arr:",arr); // Print original array
console.log("array from map:", countArr); // Print array returned from map method
console.log("number of Strings:",sum); // Print number of strings

On line 2, we apply the map() method to transform each array element into 1 if it is a string and 0 otherwise. This creates a new array of ones and zeroes.

On line 3, we use the reduce() method to sum up the values in this new array. Since each string in the original array was mapped to 1, the sum effectively represents the total count of string elements in the array assigned to arr.

Note: We can also use these methods to find the number of elements in a two-dimensional array.

Conclusion #

JavaScript’s map() and reduce() methods are powerful tools for transforming and aggregating data with minimal effort. Whether you need to modify each element in an array, sum values, flatten nested arrays, or even group objects dynamically, these methods provide elegant, readable, and efficient solutions.

By leveraging map(), you can create new arrays with transformed data effortlessly, while reduce() enables you to accumulate values into a single result. Combined, they become even more versatile—helping you solve complex problems with clean and maintainable code.

The next step? Start experimenting! Try using map() and reduce() in your JavaScript projects. Mastering these methods will significantly enhance your coding skills and efficiency, whether working with APIs, building web applications, or analyzing data.

To deepen your knowledge, explore these related blogs:

Looking to enhance your JavaScript skills further? Check out Educative’s JavaScript courses for hands-on lessons, challenges, and quizzes to accelerate your learning journey.

Some of the latest courses available on our platform include:

Frequently Asked Questions

What do map(), filter(), and reduce() methods do in JavaScript?

The map(), filter(), and reduce() methods are powerful tools for manipulating arrays in JavaScript:

  • map(): Transforms each element in an array and returns a new array.
  • filter(): Selects elements that meet a specific condition.
  • reduce(): Combines array elements into a single value, such as a sum or a grouped object.

These methods help in efficient and functional data processing.

How do you reduce an array to a map?

To reduce an array to a map in JavaScript, the reduce() method can transform the array into a key-value structure. By iterating through the array, you define how each element contributes to the final map. For instance, you can set a property of each object in the array as the key and another as the value. This approach allows for the flexible creation of maps or objects based on custom logic.

Can map() return undefined values?

Yes, the map() method can return undefined values if the callback function does not explicitly return a value. Since map() creates a new array based on the return values of the callback, any element for which the function returns undefined will appear as undefined in the resulting array. This typically happens when a return statement is missing, or the function explicitly returns undefined. To avoid this, ensure your callback function returns a meaningful value.

How is map() different from forEach()?

The map() and forEach() methods in JavaScript differ primarily in their purpose and behavior:

  • map() is used to create a new array by applying a function to each element of the original array. It always returns a transformed array of the same length as the original, leaving the original array unchanged.

  • forEach() is designed to execute a function on each array element but does not return a new array. Instead, it performs side effects like logging values or modifying external variables.

In summary, use map() when you need a transformed array and forEach() when you only need to iterate through elements without creating a new array.

Can map() skip elements in an array?

The map() method does not skip elements explicitly but does not execute the callback function on empty (sparse) slots in an array. If an array contains holes (e.g., [1, 3]), map() will preserve those empty slots in the output but will not apply the callback function to them. However, it does not allow selective skipping of elements based on conditions. If you need to filter out certain elements while transforming an array, consider using filter() before or reduce() instead of map().

Do I need to provide an initial value to reduce()?

No, providing an initial value to the reduce() method is optional, but it is often recommended.

  • If an initial value is provided, reduce() starts with that value as the first argument (prev), and the iteration begins from the first element of the array.

  • If no initial value is provided, reduce() uses the first element of the array as the initial accumulator (prev) and starts iterating from the second element. This can lead to unexpected errors when working with empty arrays, as reduce() will throw an error if there is no initial value and the array is empty.

Best practice: Always provide an initial value to ensure predictable behavior, especially when working with empty arrays.

Can reduce() handle an empty array?

The reduce() method cannot handle an empty array without an initial value and will throw a TypeError because there is no first element to use as the starting accumulator.

However, if an initial value is provided, reduce() will return that value instead of throwing an error. For example:

[].reduce((prev, curr) => prev + curr); // TypeError: Reduce of empty array with no initial value
[].reduce((prev, curr) => prev + curr, 0); // Returns 0

To avoid errors when working with potentially empty arrays, always provide an initial value in reduce().


Written By:
Tehreem Arshad

Free Resources