

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- How to return value from an asynchronous callback function in JavaScript?
- Passing a function as a callback in JavaScript
- Calculating value of a sequence based on some input using JavaScript
- Initial Value Theorem of Laplace Transform
- Initial Value Theorem of Z-Transform
- How to set initial value and auto increment in MySQL?
- Callback function in C
- Create a vertical slider with custom min, max, and initial value in Java
- Set auto increment initial value for MySQL table using ALTER command
- Sorting an array that contains the value of some weights using JavaScript
- How to return a value from a JavaScript function?
- JavaScript Array some() function
- How to create a horizontal slider with custom min, max, and initial value in Java
- Update key value where another key equals some value in MongoDB?
- Update key value where different key equals some value in MongoDB?
Advertisements