Sử dụng JavaScript reduce() để xử lý mảng hiệu quả

Sử dụng JavaScript reduce() để xử lý mảng hiệu quả

Tìm hiểu cách sử dụng hàm reduce() trong JavaScript để xử lý dữ liệu dạng mảng một cách hiệu quả. Hàm reduce() cho phép bạn thực hiện các phép tính, chuyển đổi hoặc tổng hợp dữ liệu một cách linh hoạt.
13/03/2024
11,902 Lượt xem

Giới thiệu về hàm reduce()

Hàm reduce() là một phương thức của đối tượng Array trong JavaScript. Nó được sử dụng để thực hiện một hàm lặp qua tất cả các phần tử của mảng, tích lũy một giá trị duy nhất dựa trên logic mà bạn cung cấp. Cú pháp cơ bản của reduce() như sau:

 array.reduce(callback, initialValue) 

Trong đó:

  • callback là hàm sẽ được gọi cho mỗi phần tử của mảng.
  • initialValue (tùy chọn) là giá trị khởi tạo của biến accumulator.

Callback function nhận hai đối số:

  1. accumulator: Giá trị tích lũy từ lần lặp trước.
  2. currentValue: Phần tử hiện tại của mảng.

Ví dụ đơn giản về reduce()

Giả sử chúng ta có một mảng số nguyên và muốn tính tổng của tất cả các phần tử trong mảng đó:

const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // Output: 15 

Trong ví dụ trên, hàm reduce() lặp qua các phần tử của mảng numbers và cộng chúng với nhau. Giá trị khởi tạo của accumulator là 0, và giá trị cuối cùng của accumulator (sau khi lặp qua tất cả các phần tử) là 15.

Một số ứng dụng thực tế của reduce()

Hàm reduce() không chỉ giới hạn trong việc tính tổng các phần tử mảng. Nó có thể được sử dụng trong nhiều trường hợp khác nhau, như:

Nén mảng

const flattened = [[0, 1], [2, 3], [4, 5]].reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); console.log(flattened); // Output: [0, 1, 2, 3, 4, 5] 

Trong ví dụ trên, hàm reduce() được sử dụng để nén một mảng hai chiều thành một mảng một chiều bằng cách nối tất cả các phần tử con.

Nhóm các phần tử theo một thuộc tính

const people = [ { name: 'Alice', age: 21 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 21 }, { name: 'Dave', age: 30 } ]; const groupedByAge = people.reduce((accumulator, currentValue) => { const age = currentValue.age; if (!accumulator[age]) { accumulator[age] = []; } accumulator[age].push(currentValue); return accumulator; }, {}); console.log(groupedByAge); // Output: // { // 21: [{ name: 'Alice', age: 21 }, { name: 'Charlie', age: 21 }], // 25: [{ name: 'Bob', age: 25 }], // 30: [{ name: 'Dave', age: 30 }] // } 

Trong ví dụ này, chúng ta sử dụng reduce() để nhóm các đối tượng trong mảng people theo thuộc tính age. Kết quả là một đối tượng có các khóa là tuổi và giá trị là mảng các đối tượng có cùng tuổi đó.

Thực hiện các phép tính phức tạp

const numbers = [1, 2, 3, 4, 5]; const product = numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 1); console.log(product); // Output: 120 

Trong ví dụ này, hàm reduce() được sử dụng để tính tích của tất cả các phần tử trong mảng numbers. Giá trị khởi tạo của accumulator là 1 để đảm bảo tính đúng đắn của phép nhân.

Kết luận

Hàm reduce() trong JavaScript là một công cụ mạnh mẽ để xử lý mảng. Nó cho phép bạn thực hiện các phép tính, chuyển đổi hoặc tổng hợp dữ liệu một cách linh hoạt và hiệu quả. Mặc dù có vẻ phức tạp ở giai đoạn đầu, nhưng một khi bạn nắm được cách sử dụng hàm này, nó sẽ trở thành một phần không thể thiếu trong kỹ năng lập trình JavaScript của bạn.

Các bạn có thể tham khảo thêm nguồn khác:

JavaScript Array reduce() Method - W3Schools

The reduce () method returns a single value: the function's accumulated result. The reduce () method does not execute the function for empty array elements. The reduce () method does not change the or>

A Guide To The Reduce Method In Javascript - freeCodeCamp.org

JavaScript's reduce method is one of the cornerstones of functional programming. Let's explore how it works, when you should use it, and some of the cool things it can do. A Basic Reduction Use it whe>

reduce() Function JavaScript | Implementing in reduce() Function

How does reduce () Function work in JavaScript? reduce () function takes array values as an argument and performs the reduction action by accessing array elements sequentially. Observe below syntax ca>

Array.prototype.reduce() - JavaScript | MDN - Mozilla

The reduce () method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the r>

JavaScript reduce() Method: Ultimate Guide (with Examples) - Codingem

The Array.reduce () Method in JavaScript In JavaScript, you can loop through an array with the reduce () method to produce a single value. This is a shorthand approach for creating a complex for or wh>

Javascript Reduce With Examples. Practical use cases - Medium

The reduce() function in javascriptmethod executes a reducerfunction (that you provide) on each element of the array, resulting in single output value. const array = [1, 2, 3, 4];const reducer =...>

The JavaScript Reduce Method Explained | DigitalOcean

Reduce is a method that can be difficult to understand especially with all the vague explanations that can be found on the web. There are a lot of benefits to understanding reduce as it is often used>

arrays - Javascript reduce() on Object - Stack Overflow

Javascript reduce () on Object Ask Question Asked 9 years, 8 months ago Modified 4 months ago Viewed 374k times 243 There is nice Array method reduce () to get one value from the Array. Example: [0,1,>

JavaScript Map, Reduce, and Filter - JS Array Functions Explained with ...

The reduce () method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array. Syntax arr.reduce (callback [, initialValue])>

JavaScript reduce() 方法 | 菜鸟教程

定义和用法 reduce () 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。 reduce () 可以作为一个高阶函数,用于函数的 compose。 注意: reduce () 对于空数组是不会执行回调函数的。 浏览器支持 表格中的数字表示支持该方法的第一个浏览器版本号。 语法 array.reduce (function (total, currentVal>

How to Use JavaScript Reduce(): It's Easier Than You Think

How to Use JavaScript Reduce (): It's Easier Than You Think — | by Jamie Pittman | The Startup | Medium Write Sign up Sign In 500 Apologies, but something went wrong on our end. Refresh the page,...>

JavaScript Array reduce() Method - GeeksforGeeks

Dec 14, 2022The Javascript arr.reduce () method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the re>

JavaScript Array reduce() Method - tutorialspoint.com

Javascript array reduce () method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. Syntax Its syntax is as follows − array.redu>

JavaScript Array reduce() Method - javatpoint

JavaScript Array reduce () Method The reduce () method reduces the given array into a single value by executing a reducer function. The user implements the reducer function that works on every element>

JavaScript Reduce: The Ultimate Iterator | by Mike Pottebaum ...

The first parameter of the callback function passed to reduce is the accumulator, the value ultimately returned by reduce. Each time reduce runs this callback function, a new accumulator is returned a>

Understand JavaScript Reduce With 5 Examples

The reduce() method on JavaScript arrays executes a "reducer" function on every element of the array in order, passing the return value from the previous reducer call to the next reducer call. The red>

JavaScript reduce - using reductions in JavaScript - ZetCode

Jun 16, 2022JavaScript reduce tutorial shows how to use reduction operations in JavaScript language. The reduce function The reduce function executes a reducer function on each element of the array, r>

reduce() JavaScript Array Method - Explained with Examples

Sep 26, 2022Try it on StackBlitz. In the snippet above, we used the reduce() method to sum up all the values inside the numbers array. Thereby reducing the calling array's content to a single value—th>

Array.prototype.reduce() - JavaScript | MDN - Mozilla

reduce () は、配列の反復処理の最後にコールバック関数から返される値を返します。 reduce () は 関数型プログラミング の中心的な概念です。 ここでは、どの値も変異させることができないので、配列のすべての値を積算するには、反復処理のたびに新しい積算値を返さなければなりません。 この約束事は JavaScript の reduce () にも当てはまります。 スプレッド構文 や他の可>

Javascript Map Reduce: How to Use map() with reduce() - AppDividend

To use the Javascript map reduce, first, you transform the array using map () function and then reduce that array into a single value. JavaScript array map () function creates the new array populated>

The JavaScript reduce Method | Nick McCullum

The JavaScript reduce method is one of the more complicated array methods in the JavaScript programming language because it contains so much functionality. However, once you fully understand how it wo>

JavaScript Reduce Method Made Simple - Alex Devero Blog

Nov 29, 2021The JavaScript reduce method is one of the most used array methods. It is also a part of functional programming. In this tutorial, you will learn what the reduce method is and how it works>

JavaScript Array Reduce(): Explained With Syntax and Examples

Dec 16, 2022The array reduce in JavaScript is a predefined method used to reduce an array to a single value by passing a callback function on each element of the array. It accepts a function executed>

JavaScript reduce 在做什麼? - 客座投稿 | W3HexSchool

關於 reduce MDN 的定如下: The reduce () method executes a reducer function (that you provide) on each member of the array resulting in a single output value. 簡單來說就是 reduce 方法跟其他陣列方法(例如: map 、 filter )的差別是它會>

【javascript】reduce - Qiita

JavaScript reduceメソッドについてまとめます。 reduceメソッドとは 隣り合う2つの配列要素に対して左から右へ同時に関数を適用し、単一の値にする。 というメソッドです。 例えば、「配列の中身を一つずつ足していって合計を求める」ということができます。 reduce () 以下、構文です。 array.reduce (callback [, initialValue]) array>

Guide on JavaScript Reduce: Different Use Cases Explained - BitDegree

JavaScript reduce () has an elegant way of implementing this action. It uses the callback function with two parameters: accumulator and the currentValue. The value of the accumulator can be set to any>

Javascript Array reduce() - Programiz

reduce () executes the given function for each value from left to right. reduce () does not change the original array. It is almost always safer to provide initialValue. Example 1: Sum of All Values o>

【JavaScript】reduce()の使い方 - Qiita

Feb 4, 2022reduce ()は、配列に含まれる要素を順番に取り出していき、コールバック関数を呼び出すようになっている。 配列の要素の合計を求める時などに使用される。 reduce ()の基本的な書き方は以下となる。 <対象の配列名>.reduce(<コールバック関数>,<初期値>) ここで、初期値に関しては省略可能である。 また、コールバックは順番に以下の4つの引数を取る。 1つ前のコ>

Javascript.reduce(). The Mutli-Tool of JS | by Paul Anderson | Medium

Javascript.reduce() The Mutli-Tool of JS. When it comes to reduce, there are two groups of people: I don't know reduce well enough for it to be beneficial; I wish I would have learned reduce sooner; R>


Tags:
SHARED HOSTING
70% OFF
$2.99/mo $0.90/mo
SHOP NOW
RESELLER HOSTING
25% OFF
$12.99/mo $9.74/mo
SHOP NOW