Wednesday, March 14, 2018

.reduce in JavaScript

This allows one to run a function against an array and this has this example:

const euros = [29.76, 41.85, 46.5];
const sum = euros.reduce((total, amount) => total + amount);

 
 

...and sum ends up with 118.11 in it in this example. The first two variables (named "total" and "amount" here) seem to represent first some fashion of grow-over-time-state-stash that gets returned at the end (starting with the item at position zero and warping over time with every other position) and second the immediately value out of the array when looping through it. The looping runs one less time than there are items in the collection! The link I give here suggests "index" and "array" are potential 3rd and 4th variables. The 4th is the whole of the array and the 3rd is the current position you are looping through. Again, this starts at one and not zero.

No comments:

Post a Comment