Mapped Array Sum

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of mapped array sum in JavaScript. The lab aims to provide an in-depth understanding of how to calculate the sum of an array by mapping each element to a value using the provided function. By the end of this lab, learners will be able to use Array.prototype.map() and Array.prototype.reduce() to implement the mapped array sum in their JavaScript projects.


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/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28486{{"`Mapped Array Sum`"}} javascript/data_types -.-> lab-28486{{"`Mapped Array Sum`"}} javascript/arith_ops -.-> lab-28486{{"`Mapped Array Sum`"}} javascript/comp_ops -.-> lab-28486{{"`Mapped Array Sum`"}} javascript/array_methods -.-> lab-28486{{"`Mapped Array Sum`"}} javascript/higher_funcs -.-> lab-28486{{"`Mapped Array Sum`"}} javascript/destr_assign -.-> lab-28486{{"`Mapped Array Sum`"}} end

Function to Calculate Sum of Mapped Array Elements

To calculate the sum of an array by mapping each element to a value using a provided function, use the sumBy function. This function uses Array.prototype.map() to map each element to the value returned by fn. It then uses Array.prototype.reduce() to add each value to an accumulator, which is initialized with a value of 0.

const sumBy = (arr, fn) =>
  arr
    .map(typeof fn === "function" ? fn : (val) => val[fn])
    .reduce((acc, val) => acc + val, 0);

Example Usage:

sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], (x) => x.n); // Returns 20
sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], "n"); // Returns 20

To start practicing coding with this function, open the Terminal/SSH and type node.

Summary

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

Other JavaScript Tutorials you may like