|
1 | 1 | ---
|
2 | 2 | Title: '.reduce()'
|
3 |
| -Description: 'Combines each element of an array, using a specified reducer function, and returns a single value.' |
| 3 | +Description: 'Executes a reducer function on each element of an array, resulting in a single output value.' |
4 | 4 | Subjects:
|
5 |
| - - 'Web Development' |
6 | 5 | - 'Computer Science'
|
| 6 | + - 'Web Development' |
7 | 7 | Tags:
|
8 | 8 | - 'Arrays'
|
9 | 9 | - 'Functions'
|
10 | 10 | - 'Methods'
|
| 11 | + - 'JavaScript' |
11 | 12 | CatalogContent:
|
12 | 13 | - 'introduction-to-javascript'
|
13 | 14 | - 'paths/front-end-engineer-career-path'
|
14 | 15 | ---
|
15 | 16 |
|
16 |
| -The **`.reduce()`** method combines each element of an array, using a specified reducer function, and returns a single value. |
| 17 | +JavaScript's **`.reduce()`** method is an array method that executes a reducer [function](https://www.codecademy.com/resources/docs/javascript/functions) on each element of an [array](https://www.codecademy.com/resources/docs/javascript/arrays), resulting in a single output value. It processes elements from left to right and accumulates values into a single result, making it ideal for operations like calculating sums, finding maximum values, or transforming arrays into objects. |
17 | 18 |
|
18 |
| -## Syntax |
| 19 | +## Syntax of JavaScript's `reduce()` |
19 | 20 |
|
20 | 21 | ```pseudo
|
21 |
| -array.reduce((accumulator, currentValue, index, array) => {...}, initialValue) |
| 22 | +array.reduce(callback, initialValue) |
22 | 23 | ```
|
23 | 24 |
|
24 |
| -`.reduce()` takes two arguments: |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +- `callback`: A function that executes on each element in the array. It receives four arguments: |
| 28 | + - `accumulator`: The accumulated value previously returned in the last invocation of the callback |
| 29 | + - `currentValue`: The current element being processed in the array |
| 30 | + - `currentIndex` (optional): The index of the current element being processed |
| 31 | + - `array` (optional): The array reduce was called upon |
| 32 | +- `initialValue` (optional): A value to use as the first argument to the first call of the callback |
25 | 33 |
|
26 |
| -- The first, is the reducer function that performs the reduction operation and takes four arguments: |
27 |
| - - `accumulator` is the returned value from the function. |
28 |
| - - `currentValue` is the element being iterated over. |
29 |
| - - `index` (optional) is the index of the `currentValue`. |
30 |
| - - `array` (optional) is the array the `.reduce()` was called on. |
31 |
| -- The second (optional) argument is an `initialValue` to pass to the function. |
| 34 | +**Return value:** |
32 | 35 |
|
33 |
| -The `accumulator`'s value accumulates with each iteration through the array, resulting in a single value. |
| 36 | +JavaScript's `.reduce()` method returns the single value that results from running the reducer function to completion over the entire array. |
34 | 37 |
|
35 |
| -## Example |
| 38 | +## Example 1: `array.reduce()` for Basic Sum Calculation |
| 39 | + |
| 40 | +This example demonstrates how `array.reduce` can calculate the sum of all numbers in an array: |
36 | 41 |
|
37 | 42 | ```js
|
38 |
| -const arrayOne = ['a', 'b', 'c', 'd', 'e']; |
| 43 | +const numbers = [1, 2, 3, 4, 5]; |
| 44 | + |
| 45 | +// Use reduce to calculate the sum |
| 46 | +const sum = numbers.reduce((accumulator, currentValue) => { |
| 47 | + return accumulator + currentValue; |
| 48 | +}, 0); |
39 | 49 |
|
40 |
| -// Add strings in an array. |
41 |
| -console.log( |
42 |
| - 'Adding strings:', |
43 |
| - arrayOne.reduce((acc, curr) => acc + curr) |
44 |
| -); |
| 50 | +console.log(sum); |
| 51 | +``` |
| 52 | + |
| 53 | +This example results in the following output: |
| 54 | + |
| 55 | +```shell |
| 56 | +15 |
| 57 | +``` |
45 | 58 |
|
46 |
| -// Add the values of each element together with an initial value. |
47 |
| -const arrayTwo = ['b', 'c', 'd', 'e']; |
| 59 | +The callback function adds each `currentValue` to the `accumulator`, starting with an initial value of 0. |
48 | 60 |
|
49 |
| -console.log( |
50 |
| - 'Adding with initial value:', |
51 |
| - arrayTwo.reduce((acc, curr) => acc + curr, 'a') |
52 |
| -); |
| 61 | +## Example 2: Using `array.reduce()` to Calulate Shopping Cart Total |
53 | 62 |
|
54 |
| -// Add the values of each object inside an array. |
55 |
| -const arrayThree = [{ x: 1 }, { x: 2 }, { x: 4 }]; |
| 63 | +This example shows how `.reduce()` in JavaScript can calculate the total price of items in a shopping cart, a common real-world scenario: |
56 | 64 |
|
57 |
| -console.log( |
58 |
| - 'Adding object values:', |
59 |
| - arrayThree.reduce((acc, curr) => acc + curr.x, 0) |
60 |
| -); |
| 65 | +```js |
| 66 | +const cartItems = [ |
| 67 | + { name: 'Laptop', price: 999.99 }, |
| 68 | + { name: 'Mouse', price: 25.5 }, |
| 69 | + { name: 'Keyboard', price: 75.0 }, |
| 70 | +]; |
| 71 | + |
| 72 | +// Calculate total price using reduce |
| 73 | +const totalPrice = cartItems.reduce((total, item) => { |
| 74 | + return total + item.price; |
| 75 | +}, 0); |
| 76 | + |
| 77 | +console.log(`Total cart value: $${totalPrice.toFixed(2)}`); |
61 | 78 | ```
|
62 | 79 |
|
63 |
| -This will yield the following output: |
| 80 | +This example results in the following output: |
64 | 81 |
|
65 | 82 | ```shell
|
66 |
| -Adding strings: abcde |
67 |
| -Adding with initial value: abcde |
68 |
| -Adding object values: 7 |
| 83 | +Total cart value: $1100.49 |
69 | 84 | ```
|
70 | 85 |
|
71 |
| -## Codebyte Example |
| 86 | +This demonstrates how `.reduce()` in arrays can work with objects to extract and sum specific properties. |
| 87 | + |
| 88 | +## Codebyte Example: `array.reduce()` for Finding Maximum Value |
72 | 89 |
|
73 |
| -The following example uses `.reduce()` to subtract numbers in an `expenses` array from the initial `monthlyBudget` provided: |
| 90 | +This example illustrates using the `reduce()` array method to find the largest number in an array without using `Math.max()`: |
74 | 91 |
|
75 | 92 | ```codebyte/javascript
|
76 |
| -const monthlyBudget = 3000; |
77 |
| -const expenses = [300, 200, 454, 225, 1200]; |
| 93 | +const scores = [85, 92, 78, 96, 88, 91]; |
78 | 94 |
|
79 |
| -bankBalance = expenses.reduce((acc, curr) => acc - curr, monthlyBudget); |
| 95 | +// Find the highest score using reduce |
| 96 | +const highestScore = scores.reduce((max, current) => { |
| 97 | + // Return the larger of the two values |
| 98 | + return current > max ? current : max; |
| 99 | +}); |
80 | 100 |
|
81 |
| -console.log(bankBalance); |
| 101 | +console.log(`Highest score: ${highestScore}`); |
82 | 102 | ```
|
| 103 | + |
| 104 | +Note that when no `initialValue` is provided, the first array element becomes the initial `accumulator` value, and iteration starts from the second element. |
| 105 | + |
| 106 | +## Frequently Asked Questions |
| 107 | + |
| 108 | +### 1. What does `array.reduce()` do in JS? |
| 109 | + |
| 110 | +The `array.reduce()` method in JavaScript processes each element of an array through a callback function, accumulating the results into a single value. It's commonly used for mathematical operations, data transformation, and aggregating array contents. |
| 111 | + |
| 112 | +### 2. Can `.reduce()` return array? |
| 113 | + |
| 114 | +Yes, JavaScript's `.reduce()` method can return an array. The return type depends on what you accumulate in the callback function. You can use reduce to filter, transform, or restructure arrays by returning array values from the reducer function. |
| 115 | + |
| 116 | +### 3. Does `.reduce()` have an index? |
| 117 | + |
| 118 | +Yes, the `.reduce()` JavaScript method provides access to the current index through the third parameter of the callback function (`currentIndex`). This optional parameter contains the index of the element currently being processed, starting from 0 or 1 depending on whether an initial value is provided. |
0 commit comments