Array Reduction in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring the use of the Array.prototype.reduce() method to calculate the sum of two or more numbers/arrays. We will learn how to initialize an accumulator with a value of 0 and how to use the spread operator to pass an array as individual arguments. By the end of this lab, you will have a better understanding of how to use the reduce() method in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28633{{"`Array Reduction in JavaScript`"}} javascript/data_types -.-> lab-28633{{"`Array Reduction in JavaScript`"}} javascript/arith_ops -.-> lab-28633{{"`Array Reduction in JavaScript`"}} javascript/comp_ops -.-> lab-28633{{"`Array Reduction in JavaScript`"}} javascript/higher_funcs -.-> lab-28633{{"`Array Reduction in JavaScript`"}} javascript/spread_rest -.-> lab-28633{{"`Array Reduction in JavaScript`"}} end

Here's how to find the sum of an array

To find the sum of an array of numbers, follow these steps:

  1. Open the Terminal/SSH and type node to start coding.
  2. Use the Array.prototype.reduce() method to add each value to an accumulator, which should be initialized with a value of 0.
  3. Here's the code you can use to find the sum of the array:
const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
  1. To test the sum function, use the following code examples:
sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10

By following these steps, you can easily find the sum of an array of numbers using JavaScript.

Summary

Congratulations! You have completed the Array Sum lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like