Array.reduce





'Il reduce()metodo esegue una funzione su ogni elemento dell'array per produrre (ridurlo a) un singolo valore.

'Il reduce()metodo funziona da sinistra a destra nell'array. Vedi anche reduceRight().

'Il reduce()metodo non riduce la matrice originale.

'Questo esempio trova la somma di tutti i numeri in un array:


'Esempio

'var numbers1 = [45, 4, 9, 16, 25];

'var sum = numbers1.reduce(myFunction);

'function myFunction(total, value, index, array) {

' return total + value;

'}

' Questo esempio trova la somma di tutti i numeri in un array:

' La somma e' 99


https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_reduce

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.reduce()</h2>

<p>This example finds the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduce(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value, index, array) {
return total + value;
}
</script>

</body>
</html>



'Si noti che la funzione accetta 4 argomenti:

'Il totale (il valore iniziale / valore restituito in precedenza)

'Il valore dell'oggetto

'L'indice dell'oggetto

'La matrice stessa

'L'esempio sopra non usa i parametri index e array. Puo' essere riscritto a:

'Esempio

'var numbers1 = [45, 4, 9, 16, 25];

'var sum = numbers1.reduce(myFunction);

'function myFunction(total, value) {

' return total + value;

'}


https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_reduce_2

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.reduce()</h2>

<p>This example finds the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduce(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value) {
return total + value;
}
</script>

</body>
</html>



'Il reduce()metodo puo' accettare un valore iniziale:

'Esempio

'var numbers1 = [45, 4, 9, 16, 25];

'var sum = numbers1.reduce(myFunction, 100);


'function myFunction(total, value) {

' return total + value;

'}


https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_reduce_initial

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.reduce()</h2>

<p>This example finds the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduce(myFunction, 100);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value) {
return total + value;
}
</script>

</body>
</html>












( arrayreduce.html )- by Paolo Puglisi - Modifica del 17/12/2023