

- 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
Implementing a custom function like Array.prototype.filter() function in JavaScript
Problem
We are required to write a JavaScript function that lives on the prototype Object of the Array class.
Our function should take in a callback function as the only argument. This callback function should be called for each element of the array.
And that callback function should take in two arguments the corresponding element and its index. If the callback function returns true, we should include the corresponding element in our output array otherwise we should exclude it.
Example
Following is the code −
const arr = [5, 3, 6, 2, 7, -4, 8, 10]; const isEven = num => num % 2 === 0; Array.prototype.customFilter = function(callback){ const res = []; for(let i = 0; i < this.length; i++){ const el = this[i]; if(callback(el, i)){ res.push(el); }; }; return res; }; console.log(arr.customFilter(isEven));
Output
[ 6, 2, -4, 8, 10 ]
- Related Questions & Answers
- Implementing custom function like String.prototype.split() function in JavaScript
- Implementing the Array.prototype.lastIndexOf() function in JavaScript
- Create a custom toLowerCase() function in JavaScript
- JavaScript function that lives on the prototype object of the Array class
- Importance of function prototype in C
- JavaScript Array prototype Constructor
- Accessing variables in a constructor function using a prototype method with JavaScript?
- Writing a custom URL shortener function in JavaScript
- Remove duplicate items from an array with a custom function in JavaScript
- What is function prototype in C language
- Implementing Math function and return m^n in JavaScript
- Adding a function for swapping cases to the prototype object of strings - JavaScript
- How to define custom sort function in JavaScript?
- Number prime test in JavaScript by creating a custom function?
- What is the purpose of a function prototype in C/C++?
Advertisements