1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
|
---
title: Array.prototype.reduce()
slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce
translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce
---
<div>{{JSRef}}</div>
<p> The <code><strong>reduce()</strong></code> method executes a <strong>reducer</strong> function (that you provide) on each element of the array, resulting in a single output value.</p>
<p style="direction: rtl;">متد reduce یک تابع reducer (کاهش دهنده) را بر روی هر کدام از المانهای آرایه اجرا میکند و در خروجی یک آرایه برمیگرداند. توجه داشته باشید که تابع reducer را شما باید بنویسید.</p>
<div style="direction: rtl;">{{EmbedInteractiveExample("pages/js/array-reduce.html")}}</div>
<p style="direction: rtl;">یک تابع کاهش دهنده 4 آرگومان دریافت میکند</p>
<p>The <strong>reducer</strong> function takes four arguments:</p>
<ol>
<li>Accumulator (acc) (انباشت کننده)</li>
<li>Current Value (cur) (مقدار فعلی)</li>
<li>Current Index (idx) (اندیس فعلی)</li>
<li>Source Array (src) (آرایهی مبدا)</li>
</ol>
<p>Your <strong>reducer</strong> function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.</p>
<p style="direction: rtl;">بنابراین آرگومان اول تابع reduce، کاهش دهنده، و آرگومان دوم، انباشتگر میباشد. به این ترتیب پس از اعمال کاهش دهنده بر روی هر کدام از المانهای آرایه، انباشت کننده یا اکیومیولیتور نیز اعمال اثر میکند.</p>
<h2 id="Syntax">Syntax</h2>
<pre class="syntaxbox"><var>arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])</var></pre>
<h3 id="Parameters">Parameters</h3>
<dl>
<dt><code>callback</code></dt>
<dd>A function to execute on each element in the array (except for the first, if no <code>initialValue</code> is supplied), taking four arguments:
<dl>
<dt><code>accumulator</code></dt>
<dd>The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback, or <code>initialValue</code>, if supplied (see below).</dd>
<dt><code>currentValue</code></dt>
<dd>The current element being processed in the array.</dd>
<dt><code>index</code> {{optional_inline}}</dt>
<dd>The index of the current element being processed in the array. Starts from index 0 if an <code>initialValue</code> is provided. Otherwise, starts from index 1.</dd>
<dt><code>array</code> {{optional_inline}}</dt>
<dd>The array <code>reduce()</code> was called upon.</dd>
</dl>
</dd>
<dt><code>initialValue</code> {{optional_inline}}</dt>
<dd>A value to use as the first argument to the first call of the <code>callback</code>. If no <code>initialValue</code> is supplied, the first element in the array will be used and skipped. Calling <code>reduce()</code> on an empty array without an <code>initialValue</code> will throw a <code>TypeError</code>.</dd>
</dl>
<h3 id="Return_value">Return value</h3>
<p>The single value that results from the reduction.</p>
<p style="direction: rtl;">مقدار بازگشتی مقداری واحد است.</p>
<h2 id="Description">Description</h2>
<p>The <code>reduce()</code> method executes the <code>callback</code> once for each assigned value present in the array, taking four arguments:</p>
<p style="direction: rtl;">تابع reduce، کال بک را یک بار بر روی مقدارهای الصاق شده در ارایه اعمال می کند و چهار ارگومان (ورودی) زیر را می پذیرد.</p>
<ul>
<li><code>accumulator</code></li>
<li><code>currentValue</code></li>
<li><code>currentIndex</code></li>
<li><code>array</code></li>
</ul>
<p>The first time the callback is called, <code>accumulator</code> and <code>currentValue</code> can be one of two values. If <code>initialValue</code> is provided in the call to <code>reduce()</code>, then <code>accumulator</code> will be equal to <code>initialValue</code>, and <code>currentValue</code> will be equal to the first value in the array. If no <code>initialValue</code> is provided, then <code>accumulator</code> will be equal to the first value in the array, and <code>currentValue</code> will be equal to the second.</p>
<div class="note">
<p><strong>Note:</strong> If <code>initialValue</code> is not provided, <code>reduce()</code> will execute the callback function starting at index 1, skipping the first index. If <code>initialValue</code> is provided, it will start at index 0.</p>
</div>
<p>If the array is empty and no <code>initialValue</code> is provided, {{jsxref("TypeError")}} will be thrown. If the array only has one element (regardless of position) and no <code>initialValue</code> is provided, or if <code>initialValue</code> is provided but the array is empty, the solo value will be returned <em>without </em>calling<em> <code>callback</code>.</em></p>
<p>It is usually safer to provide an <code>initialValue</code> because there are three possible outputs without <code>initialValue</code>, as shown in the following example.</p>
<p style="direction: rtl;">برای احتیاط بهتر است که همیشه یک initialValue یا مقدار اولیه درنظر گرفت زیرا در صورت در نظر نگرفتن مقدار اولیه سه حالت ممکن است رخ دهد که در مثال زیر توضیح داده شده است.</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="How_reduce_works">How reduce() works</h3>
<p>Suppose the following use of <code>reduce()</code> occurred:</p>
<pre class="brush: js">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
});
</pre>
<p>The callback would be invoked four times, with the arguments and return values in each call being as follows:</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">return value</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">first call</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">second call</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">third call</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">fourth call</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>The value returned by <code>reduce()</code> would be that of the last callback invocation (<code>10</code>).</p>
<p>You can also provide an {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} instead of a full function. The code below will produce the same output as the code in the block above:</p>
<pre class="brush: js">[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue );
</pre>
<p>If you were to provide an <code>initialValue</code> as the second argument to <code>reduce()</code>, the result would look like this:</p>
<pre class="brush: js">[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">return value</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">first call</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">second call</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">third call</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">fourth call</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">fifth call</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>The value returned by <code>reduce()</code> in this case would be <code>20</code>.</p>
<h2 id="Examples">Examples</h2>
<h3 id="Sum_all_the_values_of_an_array">Sum all the values of an array</h3>
<pre class="brush: js">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
// sum is 6
</pre>
<p>Alternatively written with an arrow function:</p>
<pre class="brush: js">var total = [ 0, 1, 2, 3 ].reduce(
( accumulator, currentValue ) => accumulator + currentValue,
0
);</pre>
<h3 id="Sum_of_values_in_an_object_array">Sum of values in an object array</h3>
<p>To sum up the values contained in an array of objects, you <strong>must</strong> supply an <code>initialValue</code>, so that each item passes through your function.</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>Alternatively written with an arrow function:</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="Flatten_an_array_of_arrays">Flatten an array of arrays</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>Alternatively written with an arrow function:</p>
<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
( accumulator, currentValue ) => accumulator.concat(currentValue),
[]
);
</pre>
<h3 id="Counting_instances_of_values_in_an_object">Counting instances of values in an object</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="Grouping_objects_by_a_property">Grouping objects by a property</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="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">// 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="Remove_duplicate_items_in_array">Remove duplicate items in array</h3>
<div class="blockIndicator note">
<p><strong>Note:</strong> If you are using an environment compatible with {{jsxref("Set")}} and {{jsxref("Array.from()")}}, you could use <code>let orderedArray = Array.from(new Set(myArray));</code> to get an array where duplicate items have been removed.</p>
</div>
<pre class="brush: js">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="Running_Promises_in_Sequence">Running Promises in Sequence</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 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) => {
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">// 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="write_map_using_reduce">write map using reduce</h3>
<pre class="brush: js">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">// 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>If you need to support truly obsolete JavaScript engines that do not support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a></code>, it is best not to polyfill <code>Array.prototype</code> methods at all, as you cannot 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>
|