aboutsummaryrefslogtreecommitdiff
path: root/files/uk/web/javascript/reference/global_objects/array/reduce
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
commit218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch)
treea9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/uk/web/javascript/reference/global_objects/array/reduce
parent074785cea106179cb3305637055ab0a009ca74f2 (diff)
downloadtranslated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip
initial commit
Diffstat (limited to 'files/uk/web/javascript/reference/global_objects/array/reduce')
-rw-r--r--files/uk/web/javascript/reference/global_objects/array/reduce/index.html578
1 files changed, 578 insertions, 0 deletions
diff --git a/files/uk/web/javascript/reference/global_objects/array/reduce/index.html b/files/uk/web/javascript/reference/global_objects/array/reduce/index.html
new file mode 100644
index 0000000000..0f9ce6e0e2
--- /dev/null
+++ b/files/uk/web/javascript/reference/global_objects/array/reduce/index.html
@@ -0,0 +1,578 @@
+---
+title: Array.prototype.reduce()
+slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce
+tags:
+ - ECMAScript 5
+ - JavaScript
+ - Reduce
+ - Масив
+ - метод
+translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce
+---
+<div>{{JSRef}}</div>
+
+<p>Метод <code><strong>reduce()</strong></code> виконує функцію <strong>reducer</strong> (функцію вказуєте ви) для кожного елемента масиву та повертає єдине значення.</p>
+
+<div>{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div>
+
+
+
+<p>Функія <strong>reducer</strong> отримує чотири параметри:</p>
+
+<ol>
+ <li>Accumulator (<em><code>acc</code></em>) - Акумулятор</li>
+ <li>Current Value (<code><em>cur</em></code>) - Поточне значення</li>
+ <li>Current Index (<em><code>idx</code></em>) - Поточний індекс</li>
+ <li>Source Array (<em><code>src</code></em>) - Вхідний масив</li>
+</ol>
+
+<p>Функція <strong>reducer</strong> повертає значення та присовює його акумулятору. Значення аккумулятора запам'ятовується через усі ітерації і повертається наприкінці як єдиний результат.</p>
+
+<h2 id="Синтакс">Синтакс</h2>
+
+<pre class="notranslate"><var>arr</var>.reduce(<var>callback</var>( <var>accumulator</var>, <var>currentValue</var>[, <var>index</var>[, <var>array</var>]] )[,
+<var>initialValue</var>])</pre>
+
+<h3 id="Параметри">Параметри</h3>
+
+<dl>
+ <dt><em><code>callback</code></em></dt>
+ <dd>Фунція, що виконується з кожним елементом масиву (приймає 4 аргументи):
+ <dl>
+ <dt><em><code>accumulator</code></em></dt>
+ <dd>Акумулює значення, які повертає <code>callback</code>. В акумуляторі зберігається попереднє значення результату виклику <code>callback</code> функції або <code>initialValue</code>, якщо воно було надано (дивись нижче).</dd>
+ <dt><em><code>currentValue</code></em></dt>
+ <dd>Поточний елемент, над яким виконується дія.</dd>
+ <dt><em><code>currentIndex</code></em>{{optional_inline}}</dt>
+ <dd>Індекс поточного елемента, над яким виконується дія. Починається із 0 індексу, якщо, було надано значення <code>initialValue</code>, інакше з 1 .</dd>
+ <dt><em><code>array</code></em>{{optional_inline}}</dt>
+ <dd>Масив, для якого було викликано <code>reduce()</code>.</dd>
+ </dl>
+ </dd>
+ <dt><em><code>initialValue</code></em>{{optional_inline}}</dt>
+ <dd>Значення, що буде використане як перший аргумент під час виклику <code>callback</code> функції. Якщо це значення не було задане, буде використано перший елемент масиву. Виклик <code>reduce()</code> на порожньому масиві без вказання initial value призведе до помилки.</dd>
+</dl>
+
+<h3 id="Значення_яке_буде_повернене">Значення, яке буде повернене</h3>
+
+<p>Значення, що зберігається в акумуляторі після останньої ітерації.</p>
+
+<h2 id="Опис">Опис</h2>
+
+<p><code>reduce()</code> виконує <em><code>callback</code> </em>функцію один раз для кожного елемента масиву за виключенням дірок (порожніх елементів). Функція отримує чотири аргументи:</p>
+
+<ul>
+ <li><em><code>accumulator</code></em></li>
+ <li><em><code>currentValue</code></em></li>
+ <li><em><code>currentIndex</code></em></li>
+ <li><em><code>array</code></em></li>
+</ul>
+
+<p>При першому виклику <em><code>callback</code> </em>функції <em><code>accumulator</code></em> і <em><code>currentValue</code></em> можуть мати одне із двох значень. Якщо значення <em><code>initialValue</code></em> задане при виклику <code>reduce()</code>, значення <em><code>accumulator</code></em> дорівнюватиме значенню <em><code>initialValue</code></em>, а <em><code>currentValue</code></em> дорівнюватиме першому елементу масиву. Якщо значення <em><code>initialValue</code></em> не задане, <em><code>accumulator</code></em> буде рівним першому елементу масиву, а <em><code>currentValue</code></em> -- другому.</p>
+
+<div class="note">
+<p><strong>Примітка:</strong> Якщо значення <code>initialValue</code> не задане, <code>reduce()</code> виконуватиме <code>callback</code> функцію починаючи з індексу 1, пропустивши перший індекс. Якщо <code>initialValue</code> задане, виконання почнеться із 0-го індексу.</p>
+</div>
+
+<p>Якщо масив порожній і значення <code>initialValue</code> не задане, буде створено помилку {{jsxref("TypeError")}}. Якщо масив складається тільки з одного елемента (незалежно від його позиції) і значення <code>initialValue</code> не задане, або якщо значення <code>initialValue</code> задане, але масив порожній, буде повернуто єдине наявне значення, а <em>функція <code>callback</code> не буде викликана</em>.</p>
+
+<p>Зазвичай безпечніше вказувати початкове значення (<code>initialValue</code>), адже без нього можливі три різні результати (див. приклад).</p>
+
+<pre class="brush: js notranslate">var maxCallback = ( acc, cur ) =&gt; Math.max( acc.x, cur.x );
+var maxCallback2 = ( max, cur ) =&gt; Math.max( max, cur );
+
+// reduce() без initialValue
+[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
+[ { x: 22 } ].reduce( maxCallback ); // { x: 22 }
+[ ].reduce( maxCallback ); // TypeError
+
+// map/reduce; краще рішення, працюватиме також для порожніх чи великих масивів
+[ { x: 22 }, { x: 42 } ].map( el =&gt; el.x )
+ .reduce( maxCallback2, -Infinity );
+</pre>
+
+<h3 id="Як_працює_reduce">Як працює reduce()</h3>
+
+<p>Нехай відбувся наступний виклик <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><code>callback</code> буде викликано чотири рази із наступними аргументами та значеннями, поверненими при кожному виклику:</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">повернене<br>
+ значення</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <th scope="row">перший виклик</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">другий виклик</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">третій виклик</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">четвертий виклик</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>Значення, повернене <code>reduce()</code> буде значенням, отриманим при останньому виклику <code>callback</code> (<code>10</code>).</p>
+
+<p>The value returned by <code>reduce()</code> would be that of the last callback invocation (<code>10</code>).</p>
+
+<p>Можна також задати {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} замість повної функції. Наступний код згенерує такий самий результат, як код у попередньому блоці.</p>
+
+<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) =&gt; accumulator + currentValue );
+</pre>
+
+<p>Якщо початкове значення (<code>initialValue)</code> задати як другий аргумент функції <code>reduce()</code>, результат буде наступним:</p>
+
+<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) =&gt; {
+ 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">повернене значення</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <th scope="row">перший виклик</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">другий виклик</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">третій виклик</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">четвертий виклик</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">
+ <p>п'ятий виклик</p>
+ </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>Значення, повернене функцією <code>reduce()</code> у цьому випадку дорівнюватиме <code>20</code>.</p>
+
+<h2 id="Приклади">Приклади</h2>
+
+<h3 id="Сума_усіх_елементів_масиву">Сума усіх елементів масиву</h3>
+
+<pre class="brush: js notranslate">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
+ return accumulator + currentValue;
+}, 0);
+// sum is 6
+
+</pre>
+
+<p>Приклад вище, реалізований за допомогою arrow function:</p>
+
+<pre class="brush: js notranslate">var total = [ 0, 1, 2, 3 ].reduce(
+  ( accumulator, currentValue ) =&gt; accumulator + currentValue,
+  0
+);</pre>
+
+<h3 id="Сума_значень_у_масиві_обєктів">Сума значень у масиві об'єктів</h3>
+
+<p>Щоб підсумувати значення, що знаходяться у масиві об'єктів, Ви <strong>повинні</strong> вказати початкове значення для того, щоб для кожного із елементів була викликана Ваша функція.</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>Також за допомогою arrow function: </p>
+
+<pre class="brush: js notranslate">var initialValue = 0;
+var sum = [{x: 1}, {x:2}, {x:3}].reduce(
+ (accumulator, currentValue) =&gt; accumulator + currentValue.x
+ ,initialValue
+);
+
+console.log(sum) // logs 6</pre>
+
+<h3 id="Сплюснути_flatten_масив_масивів">Сплюснути (flatten) масив масивів</h3>
+
+<p>Сплющення (flattening) - процес, у результаті якого із масиву масивів отримуємо один масив, що містить елементи усіх вкладених масивів.</p>
+
+<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>Також за допомогою arrow function:</p>
+
+<pre class="brush: js notranslate">var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  ( accumulator, currentValue ) =&gt; accumulator.concat(currentValue),
+  []
+);
+</pre>
+
+<h3 id="Підрахунок_кількості_однакових_значень_у_обєкті">Підрахунок кількості однакових значень у об'єкті</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="Групування_обєктів_за_властивістю_property">Групування об'єктів за властивістю (property)</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="Bonding_arrays_contained_in_an_array_of_objects_using_the_spread_operator_and_initialValue">Bonding arrays contained in an array of objects using the spread operator and 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="Видалення_повторюваних_значень_у_масиві">Видалення повторюваних значень у масиві</h3>
+
+<pre class="brush: js notranslate">let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
+let result = arr.sort().reduce((accumulator, current) =&gt; {
+ 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="Запуск_Promises_у_послідовності">Запуск Promises у послідовності</h3>
+
+<pre class="brush: js notranslate">/**
+ * 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) =&gt; promiseChain.then(currentFunction),
+    Promise.resolve(input)
+  );
+}
+
+// promise function 1
+function p1(a) {
+  return new Promise((resolve, reject) =&gt; {
+    resolve(a * 5);
+  });
+}
+
+// promise function 2
+function p2(a) {
+  return new Promise((resolve, reject) =&gt; {
+    resolve(a * 2);
+  });
+}
+
+// function 3 - will be wrapped in a resolved promise by .then()
+function f3(a) {
+ return a * 3;
+}
+
+// promise function 4
+function p4(a) {
+  return new Promise((resolve, reject) =&gt; {
+    resolve(a * 4);
+  });
+}
+
+const promiseArr = [p1, p2, f3, p4];
+runPromiseInSequence(promiseArr, 10)
+  .then(console.log);   // 1200
+</pre>
+
+<h3 id="Function_composition_enabling_piping">Function composition enabling piping</h3>
+
+<pre class="brush: js notranslate">// Building-blocks to use for composition
+const double = x =&gt; x + x;
+const triple = x =&gt; 3 * x;
+const quadruple = x =&gt; 4 * x;
+
+// Function composition enabling pipe functionality
+const pipe = (...functions) =&gt; input =&gt; functions.reduce(
+ (acc, fn) =&gt; 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="write_map_using_reduce">write map using 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) =&gt; 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 &gt;&gt;&gt; 0;
+
+ // Steps 3, 4, 5, 6, 7
+ var k = 0;
+ var value;
+
+ if (arguments.length &gt;= 2) {
+ value = arguments[1];
+ } else {
+ while (k &lt; len &amp;&amp; !(k in o)) {
+ k++;
+ }
+
+ // 3. If len is 0 and initialValue is not present,
+  // throw a TypeError exception.
+ if (k &gt;= len) {
+ throw new TypeError( 'Reduce of empty array ' +
+  'with no initial value' );
+ }
+ value = o[k++];
+ }
+
+ // 8. Repeat, while k &lt; len
+ while (k &lt; 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>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them <strong>non-enumerable</strong>.</p>
+
+<h2 id="Specifications">Specifications</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}</td>
+ <td>{{Spec2('ES5.1')}}</td>
+ <td>Initial definition. Implemented 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="Browser_compatibility">Browser compatibility</h2>
+
+<div>
+
+
+<p>{{Compat("javascript.builtins.Array.reduce")}}</p>
+</div>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li>{{jsxref("Array.prototype.reduceRight()")}}</li>
+</ul>