Mapped Array Average

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of mapping and reducing arrays in JavaScript. Specifically, we will learn how to use the averageBy() function to calculate the average of an array after mapping each element to a value using a provided function. Through hands-on exercises and examples, we will gain a deeper understanding of these powerful array methods and how they can be used to streamline our code.


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-28483{{"`Mapped Array Average`"}} javascript/data_types -.-> lab-28483{{"`Mapped Array Average`"}} javascript/arith_ops -.-> lab-28483{{"`Mapped Array Average`"}} javascript/comp_ops -.-> lab-28483{{"`Mapped Array Average`"}} javascript/array_methods -.-> lab-28483{{"`Mapped Array Average`"}} javascript/higher_funcs -.-> lab-28483{{"`Mapped Array Average`"}} javascript/destr_assign -.-> lab-28483{{"`Mapped Array Average`"}} end

Instructions for Calculating the Average of a Mapped Array

To calculate the average of an array, you can map each element to a new value using the provided function. Here are the steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.map() to map each element to the value returned by fn.
  3. Use Array.prototype.reduce() to add each mapped value to an accumulator, initialized with a value of 0.
  4. Divide the resulting array by its length to get the average.

Here's the code you can use:

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

You can test this function using the following examples:

averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], (o) => o.n); // 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], "n"); // 5

Summary

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

Other JavaScript Tutorials you may like