Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Accumulating some value over using a callback function and initial value in JavaScript
We need to write a JavaScript function that takes an array, a callback function, and an initial value to accumulate values over array iteration, similar to Array.prototype.reduce().
Problem
The goal is to create a custom reduce function that processes each array element through a callback function, accumulating a result from an initial value.
Understanding Array Reduce
The reduce method applies a callback function to each array element, building up a single result value. The callback receives the accumulator (previous result) and current element as parameters.
Custom Reduce Implementation
const arr = [1, 2, 3, 4, 5];
const sum = (accumulator, current) => accumulator + current;
Array.prototype.customReduce = function(callback, initial) {
// Handle case when no initial value provided
if (initial === undefined) {
initial = this[0];
}
let result = initial;
// Start from index 1 if using first element as initial, otherwise 0
for (let i = (initial === this[0] && arguments.length === 1) ? 1 : 0; i < this.length; i++) {
result = callback(result, this[i]);
}
return result;
};
console.log(arr.customReduce(sum, 0));
console.log(arr.customReduce(sum)); // Without initial value
15 15
How It Works
The custom reduce function:
- Takes a callback function and optional initial value
- Uses the first array element as initial value if none provided
- Iterates through the array, applying the callback to accumulate results
- Returns the final accumulated value
Example with Different Operations
const numbers = [2, 3, 4]; // Multiplication const multiply = (acc, curr) => acc * curr; console.log(numbers.customReduce(multiply, 1)); // 1 * 2 * 3 * 4 = 24 // String concatenation const words = ['Hello', ' ', 'World']; const concat = (acc, curr) => acc + curr; console.log(words.customReduce(concat, ''));
24 Hello World
Comparison with Native reduce()
| Feature | customReduce | Native reduce() |
|---|---|---|
| Basic functionality | ? | ? |
| Initial value handling | ? | ? |
| Index and array parameters | ? | ? |
| Empty array handling | Basic | Complete |
Conclusion
Custom reduce implementations help understand how accumulation works in JavaScript. While functional for basic use cases, the native reduce() method provides more robust error handling and additional callback parameters.
