Table of Contents
map : Transform Every Element in an Array
filter : Keep Only What You Need
reduce : Build Up a Single Value
Bonus: Chaining Methods Together
Home Web Front-end JS Tutorial Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`

Aug 03, 2025 am 05:54 AM
Array methods

JavaScript's array methods map, filter and reduce are used to write clear and functional code. 1. Map is used to convert each element in the array and return a new array, such as converting Celsius to Fahrenheit; 2. Filter is used to filter elements according to conditions and return a new array that meets the conditions, such as obtaining even numbers or active users; 3. Reduce is used to accumulate results, such as summing or counting frequency, and the initial value needs to be provided and returned to the accumulator; none of the three modify the original array, and can be called in chain, suitable for data processing and conversion, improving code readability and functionality.

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`

JavaScript's array methods like map , filter , and reduce are essential tools for writing clean, functional, and readable code. Once you understand how they work and when to use them, you'll find yourself reaching for loops much less often. Let's break down each method with practical examples and clear explanations.

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`

map : Transform Every Element in an Array

Use map when you want to transform each item in an array and return a new array with the updated values.

It doesn't change the original array — it creates a new one.

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`

Example: Convert temperatures from Celsius to Fahrenheit

 const celsius = [0, 10, 20, 30, 40];

const fahrenheit = celsius.map(temp => (temp * 9/5) 32);

console.log(fahrenheit); // [32, 50, 68, 86, 104]

Key points:

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`
  • Always returns a new array of the same length .
  • Great for formatting data (eg, transforming API responses).
  • Common in React for rendering lists.

? Think of map as a factory line: each item goes in, gets processed, and comes out changed.


filter : Keep Only What You Need

Use filter when you want to select a subset of items based on a condition.

It returns a new array with only the elements that pass the test.

Example: Get only even numbers

 const numbers = [1, 2, 3, 4, 5, 6, 7, 8];

const evens = numbers.filter(num => num % 2 === 0);

console.log(evens); // [2, 4, 6, 8]

Example: Find active users

 const users = [
  { name: 'Alice', active: true },
  { name: 'Bob', active: false },
  { name: 'Charlie', active: true }
];

const activeUsers = users.filter(user => user.active);

console.log(activeUsers);
// [{ name: 'Alice', active: true }, { name: 'Charlie', active: true }]

Key points:

  • The returned array can be shorter than the original.
  • The callback must return true or false .
  • You can chain it with other methods.

?️ filter is perfect when you're searching, cleaning data, or applying user filters in UIs.


reduce : Build Up a Single Value

Use reduce when you want to accumulate a result — like a sum, object, or nested structure — from an array.

It's the most powerful but also the most misunderstood.

Example: Sum all numbers

 const nums = [1, 2, 3, 4];

const sum = nums.reduce((accumulator, current) => accumulator current, 0);

console.log(sum); // 10

How it works:

  • accumulator holds the result so far.
  • current is the current element.
  • The second argument ( 0 ) is the initial value of the accumulator.

Example: Count occurrences (grouping)

 const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];

const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) 1;
  return acc;
}, {});

console.log(count);
// { apple: 3, banana: 2, orange: 1 }

Key points:

  • You can return any type: number, object, array, etc.
  • Always returns the accumulator (or updated state) in the callback.
  • Initial value is optional but highly recommended to avoid bugs.

? reduce is like folding a list into a single value — imagine gathering scattered papers into one stack.


Bonus: Chaining Methods Together

One of the best parts? You can chain these methods for powerful data processing.

Example: Get total price of expensive books

 const books = [
  { title: 'JS Guide', price: 25 },
  { title: 'React Tips', price: 30 },
  { title: 'CSS Tricks', price: 15 },
  { title: 'Node Handbook', price: 35 }
];

const total = books
  .filter(book => book.price > 20) // Keep expensive books
  .map(book => book.price) // Extract prices
  .reduce((sum, price) => sum price, 0); // Sum them

console.log(total); // 90

This is readable, functional, and avoids manual loops.


These three methods — map , filter , and reduce — are the building blocks of functional programming in JavaScript. Use them to write clearer, more predictable code. They might feel awkward at first, but once they click, you'll wonder how you ever coded without them.

Basically, just remember:

  • map → change each item
  • filter → pick some items
  • reduce → boil it all down

And don't forget: they all return new arrays (or values), so keep things immutable and safe.

The above is the detailed content of Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1504
276
Understand how to define arrays in PHP Understand how to define arrays in PHP Mar 13, 2024 pm 02:09 PM

Title: How to define arrays in PHP and specific code examples Arrays in PHP are a very important data type that can store multiple values ​​and can be accessed based on index or key value. In PHP, there are many ways to define arrays. This article will introduce some of the commonly used methods and provide specific code examples to help understand. 1. Indexed array Indexed array is the most common array type, whose elements are accessed through numerical indexes. In PHP, you can use the array() function or the simplified [] symbol to define

In-depth understanding of the practical application of array methods in Go language In-depth understanding of the practical application of array methods in Go language Mar 24, 2024 pm 12:36 PM

As a fast, concise and efficient programming language, Go language has powerful tools and functions to process arrays. In Go language, an array is a fixed-length data structure that can store a set of data elements of the same type. This article will explore array methods in Go language and provide specific practical application examples. 1. Declaring and initializing arrays In Go language, declaring and initializing an array can be done in the following ways: //Declare an array containing 5 integers vararr[5]int//

Master the common problems and solutions of array methods in Go language Master the common problems and solutions of array methods in Go language Mar 23, 2024 pm 09:21 PM

Common problems and solutions for mastering array methods in Go language. In Go language, array is a basic data structure, which consists of fixed-length elements of the same data type. When writing Go programs, we often use arrays to store a set of data. However, due to the characteristics and limitations of arrays in the Go language, some problems are more difficult when dealing with arrays. This article will introduce some common array problems and corresponding solutions, and provide specific code examples. Question 1: How to declare and initialize an array? In Go language, you can

Leveraging Array.prototype Methods for Data Manipulation in JavaScript Leveraging Array.prototype Methods for Data Manipulation in JavaScript Jul 06, 2025 am 02:36 AM

JavaScript array built-in methods such as .map(), .filter() and .reduce() can simplify data processing; 1) .map() is used to convert elements one to one to generate new arrays; 2) .filter() is used to filter elements by condition; 3) .reduce() is used to aggregate data as a single value; misuse should be avoided when used, resulting in side effects or performance problems.

What is the difference between some() and every() array methods? What is the difference between some() and every() array methods? Jun 25, 2025 am 12:35 AM

some()returnstrueifatleastoneelementpassesthetest,whileevery()returnstrueonlyifallelementspass.1.some()checksforatleastonematchandstopsearly,usefulforexistencecheckslikevalidatingactiveusersorout-of-stockproducts.2.every()ensuresallelementsmeetacondi

How does the reduce() array method work and what is a good use case for it? How does the reduce() array method work and what is a good use case for it? Jul 07, 2025 am 01:33 AM

Thereduce()methodinJavaScriptisapowerfularraytoolthatreducesanarraytoasinglevaluebyapplyingareducerfunction.1.Ittakesanaccumulatorandcurrentvalueasrequiredparameters,andoptionallyaninitialvalue.2.Commonusesincludecalculatingtotals,groupingdata,flatte

Advanced JavaScript Array Methods for Data Transformation Advanced JavaScript Array Methods for Data Transformation Jul 16, 2025 am 02:23 AM

JavaScript array methods such as map, filter and reduce can effectively simplify data processing. 1. Map is used to convert array elements and return a new array, such as extracting fields or modifying format; 2. Filter is used to filter elements that meet the conditions and return a new array, suitable for filtering invalid values or specific conditional data; 3. Reduce is used for aggregation operations, such as summing or statistics, you need to pay attention to setting the initial value and correctly returning to the accumulator. These methods do not change the original array, support chain calls, and improve code readability and maintenance.

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce` Mastering JavaScript Array Methods: `map`, `filter`, and `reduce` Aug 03, 2025 am 05:54 AM

JavaScript's array methods map, filter and reduce are used to write clear and functional code. 1. Map is used to convert each element in the array and return a new array, such as converting Celsius to Fahrenheit; 2. Filter is used to filter elements according to conditions and return a new array that meets the conditions, such as obtaining even numbers or active users; 3. Reduce is used to accumulate results, such as summing or counting frequency, and the initial value needs to be provided and returned to the accumulator; none of the three modify the original array, and can be called in chain, suitable for data processing and conversion, improving code readability and functionality.

See all articles