Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - reduce()

https://www.w3schools.com/jsref/jsref_obj_array.asp

The reduce() method reduces the array to a single value. The reduce() method executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an accumulator (result/total). Note: reduce() does not execute the function for array elements without values.

myArray.reduce(function(total, currentValue, (optional)currentIndex, (optional)arr), (optional)initialValue)

Translation: The reduce() method must receive a function or a function reference. This function or function reference looks like this:

Parameter Description
function(total,currentValue, index,arr) Required. A function to be run for each element in the array.
Function arguments:
Argument Description
total Required. The initialValue, or the previously returned value of the function
currentValue Required. The value of the current element
currentIndex Optional. The array index of the current element
arr Optional. The array object the current element belongs to
initialValue Optional. A value to be passed to the function as the initial value

https://www.w3schools.com/jsref/jsref_reduce.asp


let numbers = [1000, 100, 50];
document.getElementById("demo1").innerHTML = numbers.reduce(DoMath);

// this function is called for each array element and sent two vals each time: total & current val
function DoMath(arrayTotal, currentValue)
{
    return arrayTotal - currentValue;
}

results:

 

Demo 2 - Round all the numbers in an array, and display the sum.


// demo 2
let numbers2 = [15.5, 2.3, 1.1, 4.7];
document.getElementById("demo2").innerHTML = numbers2.reduce(GetSum, 0);
function GetSum(arrayTotal, currentValue)
{
    return arrayTotal + Math.round(currentValue);
}

results: