- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Accumulating some value over using a callback function and initial value in JavaScript
Problem
We are required to write a JavaScript function that takes in an array a callback function and an initial value.
The function should accumulate a value over the iteration of array and finally return the value just like the Array.prototype.reduce() does.
Example
Following is the code −
const arr = [1, 2, 3, 4, 5]; const sum = (a, b) => a + b; Array.prototype.customReduce = function(callback, initial){ if(!initial){ initial = this[0]; }; let res = initial; for(let i = initial === this[0] ? 1 : 0; i < this.length; i++){ res = callback(res, this[i]); }; return res; }; console.log(arr.customReduce(sum, 0));
Output
Following is the console output −
15
Advertisements