I am interested in obtaining every separate return value from the reduce() function instead of just the final total

      initialValue currentValue    position         elements      final value
first calculation       0        1               1          [0, 1, 2, 3, 4]    1
second run      1        2               2          [0, 1, 2, 3, 4]    3
third round       3        3               3          [0, 1, 2, 3, 4]    6
fourth iteration      6        4               4          [0, 1, 2, 3, 4]    10

I'm interested in having 1, 3, 6, and 10 stored in an array per call instead of the total sum 10. Therefore, I need to capture the result from each operation individually.

Answer №1

To store the return value in an array, you can follow this approach. While this method may contradict functional programming principles by mutating the results as a side effect, it still fulfills your requirements.

var array = [0, 1, 2, 3, 4];
var results = [];

array.reduce(function(previousValue, currentValue) {
    var newValue = previousValue + currentValue;
    results.push(newValue);
    return newValue;
});

// The result will be displayed as: 1,3,6,10
alert(results);

Answer №2

Avoid using the reduce method in this case. Instead, slice the array, shift a value to start a subtotal, and then use map.

var arr = [0, 1, 2, 3, 4], output = arr.slice(), subtotal = output.shift()
output = output.map(function(elem) { return subtotal += elem })
// output is [1, 3, 6, 10]

Update - However, it is possible to achieve the same result with reduce, and even with a more concise solution:

var arr = [0, 1, 2, 3, 4]
arr.reduce(function(a, b, ndx) { return a.length ? a.concat(a[ndx - 2] + b) : [a + b]})
// returns [1, 3, 6, 10]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The shuffling process in PHP may not always truly randomize the elements within an array

Currently, I am fetching results from my database and storing them in a JSON array. However, the data is being retrieved in a sequential manner based on category, for example, 1, 2, 3, 4. I would like to randomize this array so that the data is fetched in ...

Tips to avoid multiple HTTP requests being sent simultaneously

I have a collection of objects that requires triggering asynchronous requests for each object. However, I want to limit the number of simultaneous requests running at once. Additionally, it would be beneficial to have a single point of synchronization afte ...

Zebra lines overlooking unseen details

Imagine having a table where rows can be dynamically assigned classes such as .hidden, which hide those rows using CSS. The rows are styled with alternating colors, like this: tr:nth-child(even) { background-color: $light-grey; } But here's the ...

Issue with Jquery change event not functioning as expected

My webpage consists of the following HTML code: <form id="fileuploadform"> <input type="file" id="fileupload" name="fileupload" /> </form> Accompanied by this snippet of jQuery code: $(':file').change(function(){ var ...

Custom control unable to display MP3 file

Hey, I came across this awesome button that I am really interested in using: https://css-tricks.com/making-pure-css-playpause-button/ I'm currently facing two issues with it. First, I can't seem to play the sound. I've placed the mp3 file ...

Having trouble creating an alias system in discord.js and encountering errors

While developing an alias system for my Discord bot, I encountered a situation where I wanted to display the message: "if the user entered the wrong command name or alias then return: invalid command/alias". However, when implementing this logic, ...

Passing events between sibling components in Angular 2Incorporating event emission in

Having some trouble emitting an event from one component to another sibling component. I've attempted using @Output, but it seems to only emit the event to the parent component. Any suggestions? ...

Having trouble with the Moment.js diff function in your React Native project?

Within my React Native application, I have implemented Moment.js and included the following code snippet: const expDate = moment(new Date(val)).format('MM-DD-YYYY'); const nowDate = moment().format('MM-DD-YYYY'); const diff = nowDate.d ...

When a child is added to a parent in Angular UI Tree, it automatically appears in all parent nodes as well

I've been experimenting with the drag and drop feature of Angular UI Tree, and I've encountered a puzzling issue. The JSON data is fetched from my services. Upon receiving it in my controller, I need to format it correctly by adding an empty arra ...

Is my jQuery code generating a large number of DOM objects?

I am currently developing a hex dumper in JavaScript to analyze the byte data of files provided by users. To properly display a preview of the file's data, I am utilizing methods to escape HTML characters as outlined in the highest-rated answer on thi ...

Retrieve JSON data by making a POST request to a website's API

Can you help me retrieve Json data from a website API using JavaScript? I'm trying to fetch quotes from the following website: for my quotes generator page. While I have some understanding of making GET requests, it seems that this API requires POST ...

Creating a custom autocomplete search using Angular's pipes and input

Trying to implement an autocomplete input feature for any field value, I decided to create a custom pipe for this purpose. One challenge I'm facing is how to connect the component displaying my JSON data with the component housing the autocomplete in ...

Press on a specific div to automatically close another div nearby

var app = angular.module('app', []); app.controller('RedCtrl', function($scope) { $scope.OpenRed = function() { $scope.userRed = !$scope.userRed; } $scope.HideRed = function() { $scope.userRed = false; } }); app.dire ...

Altering Collada texture information during the loading process of the .jpg file

Is there a way to modify the texture image data, such as changing the .jpg header text, when loading the .jpg texture in three.js? I am curious if the texture data is accessible somewhere within the code, possibly as a string. How could I go about this? ...

Navigating within a React application using React Router 2.6.0 by triggering a redirection within a click

Currently, I am experiencing an issue while utilizing react-router for constructing a login system with firebase and react. The desired functionality involves redirecting the user to the home page upon successful authentication of their username and passw ...

Utilizing Jquery's .load function will temporarily deactivate all other functions

Season's Greetings everyone! I have a unique personal messaging system on my website that utilizes jQuery for message display and manipulation. Let's delve into the specific file that controls this functionality: <!-- Fetching and displaying ...

Error: The object 'exports' is not defined in geotiff.js at line 3

Looking to integrate the geotiff library with Angular 6.1.0 and TypeScript 2.9.2. Installed it using npm i geotiff Encountering the following error in the browser console: Uncaught ReferenceError: exports is not defined at geotiff.js:3 After r ...

Error: The function getOrders is not defined in the customerFactory

Throughout my third attempt at learning AngularJS, I've hit a roadblock. I could really use some assistance as I keep encountering the error TypeError: customerFactory.getOrders is not a function. Despite thoroughly checking for typos, I haven't ...

Sending a response in the catch block based on conditions

I am currently working on finding the correct method to handle a potential bad Fetch response. My goal is to immediately send a 500 response and halt the code execution if the Fetch response is not okay. However, if the response is acceptable, I need to ...

The slideshow fails to show correctly after being loaded from an external JavaScript file

Utilizing standard code, I have set up a Slideshow at the top of a website: HTML: <body id="Top" onload="showSlides()"> ... <div id="slides"> <div id="slide1" class="slides fade"></div> <div id="s ...