From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../reference/global_objects/array/index.html | 464 ----------------- .../reference/global_objects/array/of/index.html | 102 ---- .../global_objects/array/reduce/index.html | 579 --------------------- 3 files changed, 1145 deletions(-) delete mode 100644 files/fa/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/array/of/index.html delete mode 100644 files/fa/web/javascript/reference/global_objects/array/reduce/index.html (limited to 'files/fa/web/javascript/reference/global_objects/array') diff --git a/files/fa/web/javascript/reference/global_objects/array/index.html b/files/fa/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 8780c0cb7b..0000000000 --- a/files/fa/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,464 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - Example - - Global Objects - - JavaScript - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -
شیء Array در جاوااسکریپت یک شیء عمومی است که در ساخت آرایه ها استفاده می شود که اشیائی سطح بالا شبیه فهرست هستند.
- -
- -

ساخت یک آرایه

- -
var fruits = ['Apple', 'Banana'];
-
-console.log(fruits.length);
-// 2
-
- -

دسترسی به یک آیتم در آرایه (بر اساس نمایه)

- -
var first = fruits[0];
-// Apple
-
-var last = fruits[fruits.length - 1];
-// Banana
-
- -

اجرای حلقه روی آرایه

- -
fruits.forEach(function(item, index, array) {
-  console.log(item, index);
-});
-// Apple 0
-// Banana 1
-
- -

اضافه کردن به انتهای آرایه

- -
var newLength = fruits.push('Orange');
-// ["Apple", "Banana", "Orange"]
-
- -

حذف کردن از انتهای آرایه

- -
var last = fruits.pop(); // remove Orange (from the end)
-// ["Apple", "Banana"];
-
- -

حذف کردن از ابتدای آرایه

- -
var first = fruits.shift(); // remove Apple from the front
-// ["Banana"];
-
- -

اضافه کردن به ابتدای آرایه

- -
var newLength = fruits.unshift('Strawberry') // add to the front
-// ["Strawberry", "Banana"];
-
- -

پیدا کردن نمایه یک آیتم در یک آرایه

- -
fruits.push('Mango');
-// ["Strawberry", "Banana", "Mango"]
-
-var pos = fruits.indexOf('Banana');
-// 1
-
- -

پاک کردن یک آیتم بر اساس موقعیت نمایه

- -
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
-
-// ["Strawberry", "Mango"]
- -

پاک کردن آیتم ها بر اساس موقعیت نمایه

- -
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
-console.log(vegetables);
-// ["Cabbage", "Turnip", "Radish", "Carrot"]
-
-var pos = 1, n = 2;
-
-var removedItems = vegetables.splice(pos, n);
-// this is how to remove items, n defines the number of items to be removed,
-// from that position(pos) onward to the end of array.
-
-console.log(vegetables);
-// ["Cabbage", "Carrot"] (the original array is changed)
-
-console.log(removedItems);
-// ["Turnip", "Radish"]
- -

کپی کردن یک آرایه

- -
var shallowCopy = fruits.slice(); // this is how to make a copy
-// ["Strawberry", "Mango"]
-
- -

Syntax

- -
[element0, element1, ..., elementN]
-new Array(element0, element1[, ...[, elementN]])
-new Array(arrayLength)
- -

Parameters

- -
-
elementN
-
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below). Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
-
arrayLength
-
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
-
- -

Description

- -

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

- -

Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

- -

Accessing array elements

- -

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1. Using an invalid index number returns undefined.

- -
var arr = ['this is the first element', 'this is the second element', 'this is the last element'];
-console.log(arr[0]);              // logs 'this is the first element'
-console.log(arr[1]);              // logs 'this is the second element'
-console.log(arr[arr.length - 1]); // logs 'this is the last element'
-
- -

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error because the property name is not valid:

- -
console.log(arr.0); // a syntax error
-
- -

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

- -
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
-console.log(years.0);   // a syntax error
-console.log(years[0]);  // works properly
-
- -
renderer.3d.setTexture(model, 'character.png');     // a syntax error
-renderer['3d'].setTexture(model, 'character.png');  // works properly
-
- -

Note that in the 3d example, '3d' had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is, for this reason, that '2' and '02' would refer to two different slots on the years object and the following example could be true:

- -
console.log(years['2'] != years['02']);
-
- -

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation (but it can be accessed by dot notation in firefox 40.0a2 at least):

- -
var promise = {
-  'var'  : 'text',
-  'array': [1, 2, 3, 4]
-};
-
-console.log(promise['var']);
-
- -

Relationship between length and numerical properties

- -

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join()")}}, {{jsxref("Array.slice", "slice()")}}, {{jsxref("Array.indexOf", "indexOf()")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push()")}}, {{jsxref("Array.splice", "splice()")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

- -
var fruits = [];
-fruits.push('banana', 'apple', 'peach');
-
-console.log(fruits.length); // 3
-
- -

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

- -
fruits[5] = 'mango';
-console.log(fruits[5]); // 'mango'
-console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
-console.log(fruits.length); // 6
-
- -

Increasing the {{jsxref("Array.length", "length")}}.

- -
fruits.length = 10;
-console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
-console.log(fruits.length); // 10
-
- -

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

- -
fruits.length = 2;
-console.log(Object.keys(fruits)); // ['0', '1']
-console.log(fruits.length); // 2
-
- -

This is explained further on the {{jsxref("Array.length")}} page.

- -

Creating an array using the result of a match

- -

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

- -
// Match one d followed by one or more b's followed by one d
-// Remember matched b's and the following d
-// Ignore case
-
-var myRe = /d(b+)(d)/i;
-var myArray = myRe.exec('cdbBdbsbz');
-
- -

The properties and elements returned from this match are as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
- [2]: d
- -

Properties

- -
-
Array.length
-
The Array constructor's length property whose value is 1.
-
{{jsxref("Array.@@species", "get Array[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("Array.prototype")}}
-
Allows the addition of properties to all array objects.
-
- -

Methods

- -
-
{{jsxref("Array.from()")}}
-
Creates a new Array instance from an array-like or iterable object.
-
{{jsxref("Array.isArray()")}}
-
Returns true if a variable is an array, if not false.
-
{{jsxref("Array.of()")}}
-
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
-
- -

Array instances

- -

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
- -

Methods

- -

Mutator methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
- -

Accessor methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
- -

Iteration methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
- -

Array generic methods

- -
-

Array generics are non-standard, deprecated and will get removed in the near future.

-
- -

{{Obsolete_Header("Gecko71")}}

- -

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

- -
function isLetter(character) {
-  return character >= 'a' && character <= 'z';
-}
-
-if (Array.prototype.every.call(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

- -
if (Array.every(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

- -

These are not part of ECMAScript standards and they are not supported by non-Gecko browsers. As a standard alternative, you can convert your object to a proper array using {{jsxref("Array.from()")}}; although that method may not be supported in old browsers:

- -
if (Array.from(str).every(isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

Examples

- -

Creating an array

- -

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

- -
var msgArray = [];
-msgArray[0] = 'Hello';
-msgArray[99] = 'world';
-
-if (msgArray.length === 100) {
-  console.log('The length is 100.');
-}
-
- -

Creating a two-dimensional array

- -

The following creates a chess board as a two-dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

- -
var board = [
-  ['R','N','B','Q','K','B','N','R'],
-  ['P','P','P','P','P','P','P','P'],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  ['p','p','p','p','p','p','p','p'],
-  ['r','n','b','q','k','b','n','r'] ];
-
-console.log(board.join('\n') + '\n\n');
-
-// Move King's Pawn forward 2
-board[4][4] = board[6][4];
-board[6][4] = ' ';
-console.log(board.join('\n'));
-
- -

Here is the output:

- -
R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
-p,p,p,p,p,p,p,p
-r,n,b,q,k,b,n,r
-
-R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , ,p, , ,
- , , , , , , ,
-p,p,p,p, ,p,p,p
-r,n,b,q,k,b,n,r
-
- -

Using an array to tabulate a set of values

- -
values = [];
-for (var x = 0; x < 10; x++){
- values.push([
-  2 ** x,
-  2 * x ** 2
- ])
-};
-console.table(values)
- -

Results in

- -
0	1	0
-1	2	2
-2	4	8
-3	8	18
-4	16	32
-5	32	50
-6	64	72
-7	128	98
-8	256	128
-9	512	162
- -

(First column is the (index))

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ES7', '#sec-array-objects', 'Array')}}{{Spec2('ES7')}}New method added: {{jsxref("Array.prototype.includes()")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Array")}}

- -

See also

- - diff --git a/files/fa/web/javascript/reference/global_objects/array/of/index.html b/files/fa/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index 0c5aa6d2fa..0000000000 --- a/files/fa/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -
{{JSRef}}
- -
متد Array.of() یک آرایه ی جدید شامل آرگومان های ارسال شده به آن میباشد میسازد، صرفنظر از تعداد و نوع آرگومان ها. 
- -

تفاوت متد  Array.of() و متد سازنده ی  Array() در این میباشد که  Array.of(7) یک آرایه با یک المنت که مقدارش 7 میباشد میسازد. در حالیکه Array(7) یک آرایه ی جدید با طول 7 که شامل 7 المنت یا slot با مقدار empty میسازد نه با مقدار  undefined.

- -
Array.of(7);       // [7]
-Array.of(1, 2, 3); // [1, 2, 3]
-
-Array(7);          // array of 7 empty slots
-Array(1, 2, 3);    // [1, 2, 3]
-
- -

نحوه استفاده

- -
Array.of(element0[, element1[, ...[, elementN]]])
- -

پارامترها

- -
-
elementN
-
لیست المنت هایی که باید درون آرایه قرار بگیرند.
-
- -

مقدار بازگشتی

- -

یک نمونه جدید از {{jsxref("Array")}} .

- -

توضیحات

- -

این تابع بخشی از ECMAScript 2015 استاندارد است. برای اطلاعات بیشتر لینک های زیر مراجعه کنید:

- -

Array.of و Array.from proposal و Array.of polyfill.

- -

مثال

- -
Array.of(1);         // [1]
-Array.of(1, 2, 3);   // [1, 2, 3]
-Array.of(undefined); // [undefined]
-
- -

چند کاره سازی

- -

در صورت عدم وجود Array.of() به صورت پیشفرض، با اجرای کد زیر قبل اجرای سایر کدها، تابع  Array.of() را برای شما در کلاس Array پیاده سازی و قابل استفاده می نماید. برید حالشو ببرید.

- -
if (!Array.of) {
-  Array.of = function() {
-    return Array.prototype.slice.call(arguments);
-    // Or
-    let vals = [];
-    for(let prop in arguments){
-        vals.push(arguments[prop]);
-    }
-    return vals;
-  }
-}
-
- -

مشخصه ها

- - - - - - - - - - - - - - - - - - - - - -
مشخصهوضعیتتوضیح
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Initial definition.
- -

سازگاری با سایر مرورگرها

- -
- - -

{{Compat("javascript.builtins.Array.of")}}

-
- -

همچنین ببینید

- - diff --git a/files/fa/web/javascript/reference/global_objects/array/reduce/index.html b/files/fa/web/javascript/reference/global_objects/array/reduce/index.html deleted file mode 100644 index 6145fa772e..0000000000 --- a/files/fa/web/javascript/reference/global_objects/array/reduce/index.html +++ /dev/null @@ -1,579 +0,0 @@ ---- -title: Array.prototype.reduce() -slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce -translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce ---- -
{{JSRef}}
- -

 The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

- -

متد reduce یک تابع reducer (کاهش دهنده) را بر روی هر کدام از المان‌های آرایه اجرا می‌کند و در خروجی یک آرایه برمی‌گرداند. توجه داشته باشید که تابع reducer را شما باید بنویسید.

- -
{{EmbedInteractiveExample("pages/js/array-reduce.html")}}
- - - -

یک تابع کاهش دهنده 4 آرگومان دریافت می‌کند

- -

The reducer function takes four arguments:

- -
    -
  1. Accumulator (acc) (انباشت کننده)
  2. -
  3. Current Value (cur) (مقدار فعلی)
  4. -
  5. Current Index (idx) (اندیس فعلی)
  6. -
  7. Source Array (src) (آرایه‌ی مبدا)
  8. -
- -

Your reducer 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.

- -

بنابراین آرگومان اول تابع reduce، کاهش دهنده، و آرگومان دوم، انباشتگر می‌باشد. به این ترتیب پس از اعمال کاهش دهنده بر روی هر کدام از المان‌های آرایه، انباشت کننده یا اکیومیولیتور نیز اعمال اثر می‌کند.

- -

Syntax

- -
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
- -

Parameters

- -
-
callback
-
A function to execute on each element in the array (except for the first, if no initialValue is supplied), taking four arguments: -
-
accumulator
-
The accumulator accumulates the callback's return values. It is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).
-
currentValue
-
The current element being processed in the array.
-
index {{optional_inline}}
-
The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, starts from index 1.
-
array {{optional_inline}}
-
The array reduce() was called upon.
-
-
-
initialValue {{optional_inline}}
-
A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used and skipped. Calling reduce() on an empty array without an initialValue will throw a TypeError.
-
- -

Return value

- -

The single value that results from the reduction.

- -

مقدار بازگشتی مقداری واحد است.

- -

Description

- -

The reduce() method executes the callback once for each assigned value present in the array, taking four arguments:

- -

تابع reduce، کال بک را یک بار بر روی مقدارهای الصاق شده در ارایه اعمال می کند و چهار ارگومان (ورودی) زیر را می پذیرد.

- - - -

The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(), then accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

- -
-

Note: If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

-
- -

If the array is empty and no initialValue is provided, {{jsxref("TypeError")}} will be thrown. If the array only has one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, the solo value will be returned without calling callback.

- -

It is usually safer to provide an initialValue because there are three possible outputs without initialValue, as shown in the following example.

- -

برای احتیاط بهتر است که همیشه یک initialValue یا مقدار اولیه درنظر گرفت زیرا در صورت در نظر نگرفتن مقدار اولیه سه حالت ممکن است رخ دهد که در مثال زیر توضیح داده شده است.

- -
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 );
-
- -

How reduce() works

- -

Suppose the following use of reduce() occurred:

- -
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
-  return accumulator + currentValue;
-});
-
- -

The callback would be invoked four times, with the arguments and return values in each call being as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarrayreturn value
first call011[0, 1, 2, 3, 4]1
second call122[0, 1, 2, 3, 4]3
third call333[0, 1, 2, 3, 4]6
fourth call644[0, 1, 2, 3, 4]10
- -

The value returned by reduce() would be that of the last callback invocation (10).

- -

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:

- -
[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue );
-
- -

If you were to provide an initialValue as the second argument to reduce(), the result would look like this:

- -
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
-    return accumulator + currentValue;
-}, 10);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarrayreturn value
first call1000[0, 1, 2, 3, 4]10
second call1011[0, 1, 2, 3, 4]11
third call1122[0, 1, 2, 3, 4]13
fourth call1333[0, 1, 2, 3, 4]16
fifth call1644[0, 1, 2, 3, 4]20
- -

The value returned by reduce() in this case would be 20.

- -

Examples

- -

Sum all the values of an array

- -
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
-  return accumulator + currentValue;
-}, 0);
-// sum is 6
-
-
- -

Alternatively written with an arrow function:

- -
var total = [ 0, 1, 2, 3 ].reduce(
-  ( accumulator, currentValue ) => accumulator + currentValue,
-  0
-);
- -

Sum of values in an object array

- -

To sum up the values contained in an array of objects, you must supply an initialValue, so that each item passes through your function.

- -
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
-
- -

Alternatively written with an arrow function:

- -
var initialValue = 0;
-var sum = [{x: 1}, {x: 2}, {x: 3}].reduce(
-    (accumulator, currentValue) => accumulator + currentValue.x
-    ,initialValue
-);
-
-console.log(sum) // logs 6
- -

Flatten an array of arrays

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
-  function(accumulator, currentValue) {
-    return accumulator.concat(currentValue);
-  },
-  []
-);
-// flattened is [0, 1, 2, 3, 4, 5]
-
- -

Alternatively written with an arrow function:

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
-  ( accumulator, currentValue ) => accumulator.concat(currentValue),
-  []
-);
-
- -

Counting instances of values in an object

- -
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 }
-
- -

Grouping objects by a property

- -
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 }]
-// }
-
- -

Bonding arrays contained in an array of objects using the spread operator and initialValue

- -
// 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'
-// ]
- -

Remove duplicate items in array

- -
-

Note: If you are using an environment compatible with {{jsxref("Set")}} and {{jsxref("Array.from()")}}, you could use let orderedArray = Array.from(new Set(myArray)); to get an array where duplicate items have been removed.

-
- -
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);
- -

Running Promises in Sequence

- -
/**
- * 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
-
- -

Function composition enabling piping

- -
// 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
-
-
- -

write map using reduce

- -
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]
-
-
- -

Polyfill

- -
// 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;
-    }
-  });
-}
-
- -

If you need to support truly obsolete JavaScript engines that do not support Object.defineProperty(), it is best not to polyfill Array.prototype methods at all, as you cannot make them non-enumerable.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.reduce")}}

-
- -

See also

- - -- cgit v1.2.3-54-g00ecf