Home > Web Front-end > JS Tutorial > body text

JavaScript Array reduce() Method

王林
Release: 2024-08-28 06:05:02
Original
941 people have browsed it

JavaScript Array reduce() Method

Hi there! In this blog, you will learn about the "reduce method" and how to use it in JavaScript. So, let's get started.

Reduce is one of the array methods in JavaScript. It takes an array as input and returns a single value. The reduce method is useful when you want to process every element of an array and update a common value based on the provided callback function.

Let's dive deeper:
Reduce takes two arguments:

  1. Callback function
  2. Starting point (initial value), let's call it "result" (*Optional)

It starts with the first element of the array, passes it to the callback function, and stores the result in "result". After processing the last element, it returns the final "result".

*Optional:

If the array is empty and no initial value is provided, reduce will throw a TypeError because there's no element to serve as the initial accumulator.

If the array has only one element and no initial value is provided, reduce returns that single element without invoking the callback.

Examples:
This examples will help you to understand how and where to use the reduce method. Feel free to ask questions in comments.

Easy:
Q. Given an array, sum its elements.

Solution using reduce method.

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

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumofArray = arr.reduce(
  (result, element) => result + element,
  initialValue,
);

console.log(sumofArray);
// Expected output: 10
Copy after login

Explanation:
Initially, the result will be zero, as we have provided zero as the second argument. Then, for each element, it will add that element to the result, and lastly, the final result value will be returned.

Medium:

This example is taken from: https://leetcode.com/problems/flatten-deeply-nested-array/description/

Q. Given a multi-dimensional array arr and a depth n, return a flattened version of that array.

A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.

A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n. The depth of the elements in the first array is considered to be 0.

Solution with Reduce method :

function flattenArray(arr, depth) {
    if(depth===0) return arr;
    return arr.reduce((result,element) => {
       if(Array.isArray(element)&&depth>0) {
          result.push(...flattenArray(element, depth-1));
       } else {
          result.push(element); 
       }
       return result;
   }, []);
}
Copy after login

Explanation:
If the depth is zero, we don't need to do anything. Otherwise, we use recursion and the spread operator to add the elements to the result.

That's it! I hope you've learned about the reduce method well.

References :
Array.prototype.reduce() from MDN

The above is the detailed content of JavaScript Array reduce() Method. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!