Array of Successive Values

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to use the reduceSuccessive() function to apply a given function against an accumulator and each element in an array, returning an array of successively reduced values. We will learn how to use Array.prototype.reduce() to apply the function to the array, and store each new result. By the end of this lab, you will have a better understanding of how to use these methods to manipulate arrays 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`") subgraph Lab Skills javascript/variables -.-> lab-28632{{"`Array of Successive Values`"}} javascript/data_types -.-> lab-28632{{"`Array of Successive Values`"}} javascript/arith_ops -.-> lab-28632{{"`Array of Successive Values`"}} javascript/comp_ops -.-> lab-28632{{"`Array of Successive Values`"}} javascript/higher_funcs -.-> lab-28632{{"`Array of Successive Values`"}} end

Array of Successive Values

To create an array of successive values in JavaScript, you can use the Array.prototype.reduce() method. This method applies a function to an accumulator and each element in the array, from left to right, and returns an array of the successively reduced values.

Here's how to use reduceSuccessive function to apply the given function to the given array, storing each new result:

const reduceSuccessive = (arr, fn, acc) =>
  arr.reduce(
    (res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res),
    [acc]
  );

You can then call the reduceSuccessive function with an array, a function, and an initial value for the accumulator:

reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0);
// [0, 1, 3, 6, 10, 15, 21]

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

Summary

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

Other JavaScript Tutorials you may like