diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:15 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:15 -0500 |
commit | 4b1a9203c547c019fc5398082ae19a3f3d4c3efe (patch) | |
tree | d4a40e13ceeb9f85479605110a76e7a4d5f3b56b /files/de/web/javascript/reference/global_objects/array/reduce/index.html | |
parent | 33058f2b292b3a581333bdfb21b8f671898c5060 (diff) | |
download | translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.tar.gz translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.tar.bz2 translated-content-4b1a9203c547c019fc5398082ae19a3f3d4c3efe.zip |
initial commit
Diffstat (limited to 'files/de/web/javascript/reference/global_objects/array/reduce/index.html')
-rw-r--r-- | files/de/web/javascript/reference/global_objects/array/reduce/index.html | 564 |
1 files changed, 564 insertions, 0 deletions
diff --git a/files/de/web/javascript/reference/global_objects/array/reduce/index.html b/files/de/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..bbb3e4d57c --- /dev/null +++ b/files/de/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,564 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reduce + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +<div>{{JSRef}}</div> + +<p>Die <code><strong>reduce()</strong></code>-Methode reduziert ein Array auf einen einzigen Wert, indem es jeweils zwei Elemente (von links nach rechts) durch eine gegebene Funktion reduziert.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.reduce(<var>callback[, </var><var>initialValue]</var>)</pre> + +<h3 id="Parameter">Parameter</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Funktion, welche auf jeden Wert im Array angewandet wird und vier Argumente hat: + <dl> + <dt><code>accumulator</code></dt> + <dd>Der kumulierte Wert ist der Rückgabewert von <code>callback</code>; der in der zuvor zurückgegebene Wert des letzten Aufrufes von <code>callback</code> oder <code>initialValue</code> werden verwendet.</dd> + <dt><code>currentValue</code></dt> + <dd>Das aktuell zu verarbeitende Element des Arrays.</dd> + <dt><code>currentIndex</code>{{optional_inline}}</dt> + <dd>Der Index des aktuellen Elements des Arrays. Beginnt mit dem Index 0, falls <code>initialValue</code> angegeben wurde, ansonsten mit Index 1.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>Das Array, auf dem <code>reduce</code> abgerufen wird.</dd> + </dl> + </dd> + <dt><code>initialValue</code>{{optional_inline}}</dt> + <dd>Der Wert des ersten Arguments, der bei dem ersten Aufruf in <code>callback</code> zu benutzt wird. Wenn kein Initialwert angegeben wird, wird das erste Element des Arrays benutzt. Das Aufrufen von <code>reduce()</code> auf einem leeren Array ohne Initialwerts führt zu einem Fehler.</dd> +</dl> + +<h3 id="Rückgabewert">Rückgabewert</h3> + +<p>Der Ergebniswert der Reduzierung.</p> + +<h2 id="Beschreibung">Beschreibung</h2> + +<p><code>reduce()</code> führt die <code>callback</code>-Funktion für jedes existierende Element in dem Array aus, Ausnahme sind nicht gesetzte Werte. <code>callback</code> hat vier Parameter:</p> + +<ul> + <li><code>accumulator</code></li> + <li><code>currentValue</code></li> + <li><code>currentIndex</code></li> + <li><code>array</code></li> +</ul> + +<p>Beim ersten Aufruf von <code>callback</code> sind die Werte von <code>accumulator</code> und <code>currentValue</code> in Abhängigkeit vom Parameter <code>initialValue</code> wie folgt:</p> + +<ul> + <li>Wenn <code>initialValue</code> beim Aufruf von <code>reduce()</code> angegeben wird, ist <code>accumulator</code> gleich dem <code>initialValue</code> und <code>currentValue</code> ist gleich dem ersten Wert im Array.</li> + <li>Wenn kein <code>initialValue</code> angegeben wird, ist <code>accumulator</code> gleich mit dem ersten Wert im Array und <code>currentValue</code> wird gleich dem zweiten Wert im Array sein.</li> +</ul> + +<div class="note"> +<p><strong>Hinweis:</strong> Wenn <code>initialValue</code> nicht angegeben wird, wird <code>reduce()</code> die <code>callback</code>-Funktion startend beim Index 1 aufrufen, der erste Index wird übersprungen. Wenn <code>initialValue</code> angegeben ist, wird bei Index 0 begonnen.</p> +</div> + +<p>Wenn das Array leer ist und kein <code>initialValue</code> angegeben ist, wird ein {{jsxref("TypeError")}} erzeugt. Wenn das Array nur ein Element hat (die Position ist egal) und kein <code>initialValue</code> angegeben ist oder wenn <code>initialValue</code> angegeben ist und das Array leer ist, wird der einzelne Wert sofort zurückgegeben, ohne <code>callback</code> aufzurufen.</p> + +<p>Es ist immer sicherer <code>initialValue</code> anzugeben, weil es drei mögliche Ergebnisse ohne <code>initialValue</code> gibt, wie es im folgenden Beispiel gezeigt ist.</p> + +<pre class="brush: js">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="Wie_reduce_funktioniert">Wie reduce() funktioniert</h3> + +<p>Angenommen die folgende <code>reduce()</code> Funktion wird genutzt:</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce(function (<code>accumulator,</code> <code>currentValue</code>, <code>currentIndex</code>, array) { + return <code>accumulator</code> + currentValue; +}); +</pre> + +<p>Die <code>callback</code>-Funktion wird viermal aufgerufen, mit den Parametern und Rückgabewert für jeden Aufruf wir folgend beschrieben:</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">Rückgabewert</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">1. Aufruf</th> + <td><code>0</code></td> + <td><code>1</code></td> + <td><code>1</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>1</code></td> + </tr> + <tr> + <th scope="row">2. Aufruf</th> + <td><code>1</code></td> + <td><code>2</code></td> + <td><code>2</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>3</code></td> + </tr> + <tr> + <th scope="row">3. Aufruf</th> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>3</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>6</code></td> + </tr> + <tr> + <th scope="row">4. Aufruf</th> + <td><code>6</code></td> + <td><code>4</code></td> + <td><code>4</code></td> + <td><code>[0, 1, 2, 3, 4]</code></td> + <td><code>10</code></td> + </tr> + </tbody> +</table> + +<p>Der zurückgegebene Wert von <code>reduce()</code> ist der Rückgabewert der letzten <code>callback</code>-Funktion (<code>10</code>).</p> + +<p>Es ist zusätzlich möglich eine {{jsxref("Functions/Arrow_functions", "Arrow-Funktion","",1)}} statt einer ganzen Funktion zu benutzen. Der folgende Quelltext erzeugt die gleiche Ausgabe wie der Vorherige:</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr ); +</pre> + +<p>Wenn als zweiter Parameter von <code>reduce()</code> <code>initialValue</code> angegeben ist, wird das Ergebnis wie folgt aussehen:</p> + +<pre class="brush: js">[0, 1, 2, 3, 4].reduce((<code>accumulator</code>, currentValue, currentIndex, array) => { + return <code>accumulator</code> + 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">Rückgabewert</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">1. Aufruf</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">2. Aufruf</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">3. Aufruf</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">4. Aufruf</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">5. Aufruf</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>Der von <code>reduce()</code> zurückgegebene Wert ist in diesem Fall <code>20</code>.</p> + +<h2 id="Beispiele">Beispiele</h2> + +<h3 id="Alle_Elemente_eines_Arrays_summieren">Alle Elemente eines Arrays summieren</h3> + +<pre class="brush: js">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { + return accumulator + currentValue; +}, 0); +// sum is 6 +</pre> + +<p>Alternativ als Arrow-Funktion geschrieben:</p> + +<pre class="brush: js">var total = [ 0, 1, 2, 3 ].reduce( + ( accumulator, currentValue ) => accumulator + currentValue, + 0 +);</pre> + +<h3 id="Summe_von_Werten_in_einem_Objektarray">Summe von Werten in einem Objektarray</h3> + +<p>Um in einem Array von Objekten Werte aufzusummieren, <strong>muss</strong> ein Initialwert angegeben werden, so dass jedes Element in der Funktion durchlaufen wird.</p> + +<pre class="brush: js">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>Alternativ als Arrow-Funktion geschrieben:</p> + +<pre class="brush: js">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="Geschachtelte_Arrays_zu_einem_flachen_Array_machen">Geschachtelte Arrays zu einem flachen Array machen</h3> + +<pre class="brush: js">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>Alternativ als Arrow-Funktion geschrieben:</p> + +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( + ( accumulator, currentValue ) => accumulator.concat(currentValue), + [] +); +</pre> + +<h3 id="Zählen_von_Instanzen_eines_Wertes_in_einem_Objekt">Zählen von Instanzen eines Wertes in einem Objekt</h3> + +<pre class="brush: js">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="Objekte_nach_einer_Eigenschaft_gruppieren">Objekte nach einer Eigenschaft gruppieren</h3> + +<pre class="brush: js">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="Verbinden_von_Arrays_in_einem_Array_von_Objekten_mithilfe_des_Spread-Operators_und_von_initialValue"><span id="result_box" lang="de"><span>Verbinden von Arrays in einem Array von Objekten mithilfe des Spread-Operators und von <code>initialValue</code></span></span></h3> + +<pre class="brush: js">// 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="Duplikate_in_einem_Array_entfernen">Duplikate in einem Array entfernen</h3> + +<pre class="brush: js">let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4]; +let result = arr.sort().reduce((accumulator, current) => { + const length = accumulator.length; + if (length === 0 || accumulator[length - 1] !== current) { + accumulator.push(current); + } + return accumulator; +}, []); +console.log(result); //[1,2,3,4,5] +</pre> + +<h3 id="Sequenzielle_Abarbeitung_von_Promises">Sequenzielle Abarbeitung von Promises</h3> + +<pre class="brush: js">/** + * Runs promises from array of functions that can return promises + * in chained manner + * + * @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 - will wrapped in a resolved promise by .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="Funktionskomposition_ermöglicht_Pipelining">Funktionskomposition ermöglicht Pipelining</h3> + +<pre class="brush: js">// Building-blocks to use for composition +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 +); + +// Composed functions for multiplication of specific values +const multiply6 = pipe(double, triple); +const multiply9 = pipe(triple, triple); +const multiply16 = pipe(quadruple, quadruple); +const multiply24 = pipe(double, triple, quadruple); + +// Usage +multiply6(6); // 36 +multiply9(9); // 81 +multiply16(16); // 256 +multiply24(10); // 240 +</pre> + +<h3 id="Mapfunktion_mit_reduce">Mapfunktion mit reduce</h3> + +<pre class="brush: js">if (!Array.prototype.map) { + Array.prototype.map = function(callback, thisArg) { + return this.reduce(function(mappedArray, currentValue, index, array) { + mappedArray[index] = callback.call(thisArg, currentValue, index, array); + return mappedArray; + }, []); + }; +} + +[1, 2, , 3].map( + (currentValue, index, array) => currentValue + index + array.length +); // [5, 7, , 10] + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// 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>Wenn es wirklich notwendig ist veraltete JavaScript-Umgebungen zu benutzen, die <code><a href="/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a></code> nicht unterstützen, ist es besser <code>Array.prototype</code> nicht komplett zu ersetzen, weil man es nicht non-enumerable machen kann.</p> + +<h2 id="Spezifikationen">Spezifikationen</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Spezification</th> + <th scope="col">Status</th> + <th scope="col">Kommentar</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initiale Definition. Implementiert 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="Browserkompatibilität">Browserkompatibilität</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.reduce")}}</p> +</div> + +<h2 id="Siehe_auch">Siehe auch</h2> + +<ul> + <li>{{jsxref("Array.prototype.reduceRight()")}}</li> +</ul> |