Skip to content

Commit 4ea22fb

Browse files
[Edit]: Js Arrays .reduce() (#7405)
* [Edit]: Js Arrays `.reduce()` * Update content/javascript/concepts/arrays/terms/reduce/reduce.md * Update content/javascript/concepts/arrays/terms/reduce/reduce.md * Update content/javascript/concepts/arrays/terms/reduce/reduce.md ---------
1 parent b9e7400 commit 4ea22fb

File tree

1 file changed

+78
-42
lines changed
  • content/javascript/concepts/arrays/terms/reduce

1 file changed

+78
-42
lines changed
Lines changed: 78 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,82 +1,118 @@
11
---
22
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.'
44
Subjects:
5-
- 'Web Development'
65
- 'Computer Science'
6+
- 'Web Development'
77
Tags:
88
- 'Arrays'
99
- 'Functions'
1010
- 'Methods'
11+
- 'JavaScript'
1112
CatalogContent:
1213
- 'introduction-to-javascript'
1314
- 'paths/front-end-engineer-career-path'
1415
---
1516

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

18-
## Syntax
19+
## Syntax of JavaScript's `reduce()`
1920

2021
```pseudo
21-
array.reduce((accumulator, currentValue, index, array) => {...}, initialValue)
22+
array.reduce(callback, initialValue)
2223
```
2324

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
2533

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:**
3235

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

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

3742
```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);
3949

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+
```
4558

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

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
5362

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

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)}`);
6178
```
6279

63-
This will yield the following output:
80+
This example results in the following output:
6481

6582
```shell
66-
Adding strings: abcde
67-
Adding with initial value: abcde
68-
Adding object values: 7
83+
Total cart value: $1100.49
6984
```
7085

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
7289

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()`:
7491

7592
```codebyte/javascript
76-
const monthlyBudget = 3000;
77-
const expenses = [300, 200, 454, 225, 1200];
93+
const scores = [85, 92, 78, 96, 88, 91];
7894
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+
});
80100
81-
console.log(bankBalance);
101+
console.log(`Highest score: ${highestScore}`);
82102
```
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

Comments
 (0)