Suggest an editImprove this articleRefine the answer for “reduce() in an array”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)`reduce()` is one of the most powerful and versatile tools for working with arrays in JavaScript. **Key point:** it is used to sequentially reduce an array to a single value: a number, a string, an object, an array, and so on.Shown above the full answer for quick recall.Answer (EN)ImageThe `reduce()` method is one of the most powerful and versatile tools for working with arrays in JavaScript. It is used to **sequentially reduce** an array **to a single value**: a number, a string, an object, an array, and so on. ## Syntax ```javascript const result = array.reduce((accumulator, currentValue, index, array) => { return newAccumulatorValue; }, initialValue); ``` ### Parameters: | Argument | Description | |---|---| | `accumulator` | the accumulated value (what is returned on each iteration) | | `currentValue` | the current array element | | `index` | the index of the current element | | `array` | the array itself | | `initialValue` | the accumulator's starting value (optional, but **strongly recommended**!) | ## Example 1. Sum of numbers in an array ```javascript const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((acc, num) => acc + num, 0); console.log(sum); // 10 ``` Explanation: 1. `acc = 0` (initial value) 2. 0 + 1 → 1 3. 1 + 2 → 3 4. 3 + 3 → 6 5. 6 + 4 → 10 ## Example 2. Counting elements by a condition ```javascript const users = [ { name: 'Tim', age: 25 }, { name: 'Alex', age: 17 }, { name: 'John', age: 30 } ]; const adultsCount = users.reduce((acc, user) => { return user.age >= 18 ? acc + 1 : acc; }, 0); console.log(adultsCount); // 2 ``` > `reduce()` is often used for aggregation - counts, statistics, merges, and so on. ## Example 3. Converting an array into an object ```javascript const fruits = ['apple', 'banana', 'cherry']; const fruitMap = fruits.reduce((acc, fruit, index) => { acc[index] = fruit; return acc; }, {}); console.log(fruitMap); // { 0: 'apple', 1: 'banana', 2: 'cherry' } ``` > Very convenient for converting data into another structure. ## Example 4. Merging an array of objects ```javascript const products = [ { price: 10 }, { price: 20 }, { price: 30 } ]; const total = products.reduce((acc, item) => acc + item.price, 0); console.log(total); // 60 ``` ## If you don't specify initialValue ```javascript const arr = [1, 2, 3]; const sum = arr.reduce((acc, num) => acc + num); console.log(sum); // 6 ``` Here: - `acc` on the first iteration = `1` (the first element) - `currentValue` = `2`, then `3` > If the array is **empty** and there is no `initialValue` → you get an **error**: ```javascript [].reduce((acc, x) => acc + x); // TypeError ``` So **always specify an initial value**, especially for empty arrays. ## Frequent errors 1. **Missing** `return` ```javascript arr.reduce((acc, num) => { acc + num }, 0); // undefined ``` Fix it: ```javascript arr.reduce((acc, num) => { return acc + num }, 0); ``` 2. **Wrong type of initial value** ```javascript ['1', '2', '3'].reduce((acc, n) => acc + n, 0); // '0123', a string ``` Convert explicitly: ```javascript ['1', '2', '3'].reduce((acc, n) => acc + Number(n), 0); // 6 ``` ## When to use reduce() | Goal | Does `reduce()` fit | |---|---| | Sum or product of numbers | Yes | | Counting statistics or totals | Yes | | Converting an array into an object | Yes | | Concatenating strings or arrays | Yes | | Transforming each element | No - use `map()` instead | | Selecting elements | No - use `filter()` instead | ## In short: > `reduce()` is a "universal Swiss army knife": it reduces an array to **a single final value**. A formula to remember: `arr.reduce((acc, elem) => newValue, initialValue)` ## Comparison with other methods | Method | What it does | Returns | Can break out of the loop | |---|---|---|---| | **forEach()** | Iterates over elements | `undefined` | No | | **map()** | Transforms elements | A new array | No | | **filter()** | Selects elements | A new array | No | | **find()** | Finds the first matching element | The element or `undefined` | Yes | | **reduce()** | Reduces the whole array to one value | Any type (number, string, object, etc.) | Can via logic |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.