diff options
Diffstat (limited to 'files/it/web/javascript/reference/global_objects/array/reduce')
-rw-r--r-- | files/it/web/javascript/reference/global_objects/array/reduce/index.html | 576 |
1 files changed, 576 insertions, 0 deletions
diff --git a/files/it/web/javascript/reference/global_objects/array/reduce/index.html b/files/it/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..de063df929 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,576 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +tags: + - Array + - Array method + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reduce + - Referenza +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +<div>{{JSRef}}</div> + +<p>Il metodo <code><strong>reduce()</strong></code> esegue una funzione <strong>reducer</strong> (che tu fornisci) su ogni elemento dell'array, risultante in un unico output.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div> + +<div>I sorgenti per questo esempio interattivo è disponibile su un repository GitHub. Se desideri contribuire al progetto, clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e inviaci una pull request.</div> + +<p>La funzione <strong>reducer</strong> accetta quattro argomenti:</p> + +<ol> + <li>Accumulatore (acc)</li> + <li>Valore corrente (cur)</li> + <li>Indice corrente (idx)</li> + <li>Array sul quale viene eseguito il metodo (src)</li> +</ol> + +<p>Il valore restituito della funzione <strong>reducer</strong> viene assegnato all'accumulatore, il cui valore viene memorizzato attraverso ogni iterazione nell'intero array e in definitiva, diventa il valore finale finale singolo.</p> + +<h2 id="Sintassi">Sintassi</h2> + +<pre class="syntaxbox notranslate"><var>arr.reduce(callback(accumulator, currentValue[, index[, array]]) [, initialValue])</var></pre> + +<h3 id="Parametri">Parametri</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Una funzione da eseguire su ogni elemento dell'array (tranne il primo, se non viene fornita <code>initialValue</code>), accetta 4 argomenti: + <dl> + <dt><code>accumulator</code></dt> + <dd>L'accumulatore accumula i valori di ritorno del callback. È il valore accumulato precedentemente restituito nell'ultima chiamata del callback o <code>initialValue</code>, se fornito (vedere di seguito).</dd> + <dt><code>currentValue</code></dt> + <dd>L'elemento corrente in elaborazione nell'array.</dd> + <dt><code>index</code> {{optional_inline}}</dt> + <dd>L'indice dell'elemento corrente in elaborazione nell'array. Inizia dall'indice 0 se viene fornito <code>initialValue</code> Altrimenti, inizia dall'indice 1.</dd> + <dt><code>array</code> {{optional_inline}}</dt> + <dd>L'array a cui viene applicato <code>reduce()</code>.</dd> + </dl> + </dd> + <dt><code>initialValue</code> {{optional_inline}}</dt> + <dd>Un valore da utilizzare come primo argomento della prima chiamata del <code>callback</code>. Se non viene fornito <code>initialValue</code> il primo elemento dell'array verrà utilizzato e saltato. Chiamare <code>reduce()</code> su un array vuoto senza <code>initialValue</code> genererà un <code>TypeError</code>.</dd> +</dl> + +<h3 id="Valore_di_ritorno">Valore di ritorno</h3> + +<p>Il singolo valore che risulta dalla riduzione.</p> + +<h2 id="Descrizione">Descrizione</h2> + +<p>Il metodo <code>reduce()</code> esegue il <code>callback</code> una volta per ogni valore assegnato presente nell'array, prendendo quattro argomenti:</p> + +<ul> + <li><code>accumulator</code></li> + <li><code>currentValue</code></li> + <li><code>currentIndex</code></li> + <li><code>array</code></li> +</ul> + +<p>La prima volta che viene chiamato il callback, <code>accumulator</code> e <code>currentValue</code> possono essere uno dei due valori. Se <code>initialValue</code> viene fornito nella chiamata a <code>reduce()</code>, <code>accumulator</code> sarà uguale a <code>initialValue</code>, e <code>currentValue</code> sarà uguale al primo valore nell'array. Se non viene fornito alcun valore <code>initialValue</code>, <code>accumulator</code> sarà uguale al primo valore dell'array e <code>currentValue</code> sarà uguale al secondo.</p> + +<div class="note"> +<p><strong>Note:</strong> Se non viene fornito <code>initialValue</code>, <code>reduce()</code> eseguirà la funzione di callback a partire dall'indice 1, saltando il primo indice. Se viene fornito <code>initialValue</code>, inizierà dall'indice 0.</p> +</div> + +<p>Se l'array è vuoto e non viene fornito <code>initialValue</code> verrà generato un {{jsxref("TypeError")}}. Se l'array ha solo un elemento (indipendentemente dalla posizione) e non viene fornito <code>initialValue</code>, o se è fornito <code>initialValue</code> ma l'array è vuoto, il valore solo verrà restituito <em>senza</em> chiamare <em><code>callback</code>.</em></p> + +<p>Di solito è più sicuro fornire <code>initialValue</code> perché ci sono tre output possibili senza <code>initialValue</code>, come mostrato nell'esempio seguente.</p> + +<pre class="brush: js notranslate">var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x ); +var maxCallback2 = ( max, cur ) => Math.max( max, cur ); + +// reduce() without initialValue +[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42 +[ { x: 22 } ].reduce( maxCallback ); // { x: 22 } +[ ].reduce( maxCallback ); // TypeError + +// map/reduce; better solution, also works for empty or larger arrays +[ { x: 22 }, { x: 42 } ].map( el => el.x ) + .reduce( maxCallback2, -Infinity ); +</pre> + +<h3 id="Come_funziona_reduce">Come funziona reduce()</h3> + +<p>Supponiamo che si sia verificato il seguente uso di <code>reduce()</code>:</p> + +<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { + return accumulator + currentValue; +}); +</pre> + +<p>Il callback verrebbe invocato quattro volte, con gli argomenti e i valori restituiti in ogni chiamata come segue:</p> + +<table> + <thead> + <tr> + <th scope="col"><code>callback</code></th> + <th scope="col"><code>accumulator</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>currentIndex</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">valore ritornato</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">prima chiamata</th> + <td><code>0</code></td> + <td><code>1</code></td> + <td>1</td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>1</code></td> + </tr> + <tr> + <th scope="row">seconda chiamata</th> + <td><code>1</code></td> + <td><code>2</code></td> + <td>2</td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>3</code></td> + </tr> + <tr> + <th scope="row">terza chiamata</th> + <td><code>3</code></td> + <td><code>3</code></td> + <td>3</td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>6</code></td> + </tr> + <tr> + <th scope="row">quarta chiamata</th> + <td><code>6</code></td> + <td><code>4</code></td> + <td>4</td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + </tbody> +</table> + +<p>Il valore restituito da <code>reduce()</code> sarà quello dell'ultima chiamata del callback (<code>10</code>).</p> + +<p>È inoltre possibile fornire una {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} al posto di una funzione completa. Il seguente codice produrrà lo stesso output del codice nel blocco sopra riportato:</p> + +<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue ); +</pre> + +<p>Se dovessi fornire <code>initialValue</code> come secondo argomento a <code>reduce()</code>, il risultato sarebbe simile a questo:</p> + +<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { + return accumulator + currentValue; +}, 10); +</pre> + +<table> + <thead> + <tr> + <th scope="col"><code>callback</code></th> + <th scope="col"><code>accumulator</code></th> + <th scope="col"><code>currentValue</code></th> + <th scope="col"><code>currentIndex</code></th> + <th scope="col"><code>array</code></th> + <th scope="col">valore restituito</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">prima chiamata</th> + <td><code>10</code></td> + <td><code>0</code></td> + <td><code>0</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + <tr> + <th scope="row">seconda chiamata</th> + <td><code>10</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>11</code></td> + </tr> + <tr> + <th scope="row">terza chiamata</th> + <td><code>11</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>13</code></td> + </tr> + <tr> + <th scope="row">quarta chiamata</th> + <td><code>13</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>16</code></td> + </tr> + <tr> + <th scope="row">quinta chiamata</th> + <td><code>16</code></td> + <td><code>4</code></td> + <td><code>4</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>20</code></td> + </tr> + </tbody> +</table> + +<p>Il valore restituito da <code>reduce()</code> in questo caso sarebbe <code>20</code>.</p> + +<h2 id="Esempi">Esempi</h2> + +<h3 id="Sommare_tutti_i_valori_di_un_array">Sommare tutti i valori di un array</h3> + +<pre class="brush: js notranslate">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { + return accumulator + currentValue; +}, 0); +// sum è 6 + +</pre> + +<p>In alternativa scritto con una arrow function:</p> + +<pre class="brush: js notranslate">var total = [ 0, 1, 2, 3 ].reduce( + ( accumulator, currentValue ) => accumulator + currentValue, + 0 +);</pre> + +<h3 id="Somma_dei_valori_in_un_array_di_oggetti">Somma dei valori in un array di oggetti</h3> + +<p>Per riassumere i valori contenuti in un array di oggetti, <strong>devi</strong> fornire <code>initialValue</code>, in modo che ogni elemento passi attraverso la tua funzione</p> + +<pre class="brush: js notranslate">var initialValue = 0; +var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(function (accumulator, currentValue) { + return accumulator + currentValue.x; +},initialValue) + +console.log(sum) // logs 6 +</pre> + +<p>In alternativa scritto con una arrow function:</p> + +<pre class="brush: js notranslate">var initialValue = 0; +var sum = [{x: 1}, {x: 2}, {x: 3}].reduce( + (accumulator, currentValue) => accumulator + currentValue.x + ,initialValue +); + +console.log(sum) // logs 6</pre> + +<h3 id="Appiattire_una_serie_di_array">Appiattire una serie di array</h3> + +<pre class="brush: js notranslate">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( + function(accumulator, currentValue) { + return accumulator.concat(currentValue); + }, + [] +); +// flattened is [0, 1, 2, 3, 4, 5] +</pre> + +<p>In alternativa scritto con una arrow function:</p> + +<pre class="brush: js notranslate">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( + ( accumulator, currentValue ) => accumulator.concat(currentValue), + [] +); +</pre> + +<h3 id="Conteggio_delle_istanze_di_valori_in_un_oggetto">Conteggio delle istanze di valori in un oggetto</h3> + +<pre class="brush: js notranslate">var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; + +var countedNames = names.reduce(function (allNames, name) { + if (name in allNames) { + allNames[name]++; + } + else { + allNames[name] = 1; + } + return allNames; +}, {}); +// countedNames is: +// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 } +</pre> + +<h3 id="Raggruppamento_di_oggetti_in_base_a_una_proprietà">Raggruppamento di oggetti in base a una proprietà</h3> + +<pre class="brush: js notranslate">var people = [ + { name: 'Alice', age: 21 }, + { name: 'Max', age: 20 }, + { name: 'Jane', age: 20 } +]; + +function groupBy(objectArray, property) { + return objectArray.reduce(function (acc, obj) { + var key = obj[property]; + if (!acc[key]) { + acc[key] = []; + } + acc[key].push(obj); + return acc; + }, {}); +} + +var groupedPeople = groupBy(people, 'age'); +// groupedPeople is: +// { +// 20: [ +// { name: 'Max', age: 20 }, +// { name: 'Jane', age: 20 } +// ], +// 21: [{ name: 'Alice', age: 21 }] +// } +</pre> + +<h3 id="Array_di_legame_contenuti_in_una_serie_di_oggetti_che_utilizzano_lo_spread_operator_e_initialValue">Array di legame contenuti in una serie di oggetti che utilizzano lo spread operator e initialValue</h3> + +<pre class="brush: js notranslate">// friends - an array of objects +// where object field "books" - list of favorite books +var friends = [{ + name: 'Anna', + books: ['Bible', 'Harry Potter'], + age: 21 +}, { + name: 'Bob', + books: ['War and peace', 'Romeo and Juliet'], + age: 26 +}, { + name: 'Alice', + books: ['The Lord of the Rings', 'The Shining'], + age: 18 +}]; + +// allbooks - list which will contain all friends' books + +// additional list contained in initialValue +var allbooks = friends.reduce(function(accumulator, currentValue) { + return [...accumulator, ...currentValue.books]; +}, ['Alphabet']); + +// allbooks = [ +// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace', +// 'Romeo and Juliet', 'The Lord of the Rings', +// 'The Shining' +// ]</pre> + +<h3 id="Rimuovi_gli_elementi_duplicati_nellarray">Rimuovi gli elementi duplicati nell'array</h3> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> Se si utilizza un ambiente compatibile con {{jsxref("Set")}} e {{jsxref("Array.from()")}}, è possibile utilizzare <code>let orderedArray = Array.from(new Set(myArray));</code> per ottenere un array in cui sono stati rimossi gli elementi duplicati.</p> +</div> + +<pre class="brush: js notranslate">var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']; +var myOrderedArray = myArray.reduce(function (accumulator, currentValue) { + if (accumulator.indexOf(currentValue) === -1) { + accumulator.push(currentValue); + } + return accumulator +}, []) + +console.log(myOrderedArray);</pre> + +<h3 id="Eseguire_le_Promises_in_Sequenza">Eseguire le Promises in Sequenza</h3> + +<pre class="brush: js notranslate">/** + * Esegue promises da un array di funzioni che possono restituire promises + * in modo concatenato + * + * @param {array} arr - promise arr + * @return {Object} promise object + */ +function runPromiseInSequence(arr, input) { + return arr.reduce( + (promiseChain, currentFunction) => promiseChain.then(currentFunction), + Promise.resolve(input) + ); +} + +// promise function 1 +function p1(a) { + return new Promise((resolve, reject) => { + resolve(a * 5); + }); +} + +// promise function 2 +function p2(a) { + return new Promise((resolve, reject) => { + resolve(a * 2); + }); +} + +// function 3 - sarà avvolta in una promise risolta da .then() +function f3(a) { + return a * 3; +} + +// promise function 4 +function p4(a) { + return new Promise((resolve, reject) => { + resolve(a * 4); + }); +} + +const promiseArr = [p1, p2, f3, p4]; +runPromiseInSequence(promiseArr, 10) + .then(console.log); // 1200 +</pre> + +<h3 id="Composizione_funzionale_per_tubazioni">Composizione funzionale per tubazioni</h3> + +<pre class="brush: js notranslate">// Elementi da utilizzare per la composizione +const double = x => x + x; +const triple = x => 3 * x; +const quadruple = x => 4 * x; + +// Function composition enabling pipe functionality +const pipe = (...functions) => input => functions.reduce( + (acc, fn) => fn(acc), + input +); + +// Funzioni composte per la moltiplicazione di valori specifici +const multiply6 = pipe(double, triple); +const multiply9 = pipe(triple, triple); +const multiply16 = pipe(quadruple, quadruple); +const multiply24 = pipe(double, triple, quadruple); + +// Utilizzo +multiply6(6); // 36 +multiply9(9); // 81 +multiply16(16); // 256 +multiply24(10); // 240 + +</pre> + +<h3 id="Scrivere_map_usando_reduce">Scrivere map usando reduce</h3> + +<pre class="brush: js notranslate">if (!Array.prototype.mapUsingReduce) { + Array.prototype.mapUsingReduce = function(callback, thisArg) { + return this.reduce(function(mappedArray, currentValue, index, array) { + mappedArray[index] = callback.call(thisArg, currentValue, index, array); + return mappedArray; + }, []); + }; +} + +[1, 2, , 3].mapUsingReduce( + (currentValue, index, array) => currentValue + index + array.length +); // [5, 7, , 10] + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js notranslate">// Production steps of ECMA-262, Edition 5, 15.4.4.21 +// Reference: http://es5.github.io/#x15.4.4.21 +// https://tc39.github.io/ecma262/#sec-array.prototype.reduce +if (!Array.prototype.reduce) { + Object.defineProperty(Array.prototype, 'reduce', { + value: function(callback /*, initialValue*/) { + if (this === null) { + throw new TypeError( 'Array.prototype.reduce ' + + 'called on null or undefined' ); + } + if (typeof callback !== 'function') { + throw new TypeError( callback + + ' is not a function'); + } + + // 1. Let O be ? ToObject(this value). + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // Steps 3, 4, 5, 6, 7 + var k = 0; + var value; + + if (arguments.length >= 2) { + value = arguments[1]; + } else { + while (k < len && !(k in o)) { + k++; + } + + // 3. If len is 0 and initialValue is not present, + // throw a TypeError exception. + if (k >= len) { + throw new TypeError( 'Reduce of empty array ' + + 'with no initial value' ); + } + value = o[k++]; + } + + // 8. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kPresent be ? HasProperty(O, Pk). + // c. If kPresent is true, then + // i. Let kValue be ? Get(O, Pk). + // ii. Let accumulator be ? Call( + // callbackfn, undefined, + // « accumulator, kValue, k, O »). + if (k in o) { + value = callback(value, o[k], k, o); + } + + // d. Increase k by 1. + k++; + } + + // 9. Return accumulator. + return value; + } + }); +} +</pre> + +<p>Se hai bisogno di supportare motori JavaScript veramente obsoleti che non supportano <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a></code>, è meglio non applicare polyfills ai metodi di <code>Array.prototype</code>, poiché non puoi renderli non enumerabili.</p> + +<h2 id="Specifiche">Specifiche</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specifica</th> + <th scope="col">Stato</th> + <th scope="col">Commento</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definizione iniziale Implementato in JavaScript 1.8.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2> + +<p>La tabella di compatibilità in questa pagina è generata a partire da dati strutturati. Se desideri contribuire ai dati, visita <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e inviaci una pull request.</p> + +<div> +<p>{{Compat("javascript.builtins.Array.reduce")}}</p> +</div> + +<h2 id="Vedi_anche">Vedi anche</h2> + +<ul> + <li>{{jsxref("Array.prototype.reduceRight()")}}</li> +</ul> |