Map
It returns new array from original array, by performing some operations( callback function) on each array items. It does not alter the original array.
const nums = [1, 2, 3, 4];
const double = nums.map((num, i, arr) => num * 2);
console.log(double); // [2, 4, 6, 8]
Implementation
Array.prototype.myMap = function (cb) {
let output = [];
for (let i = 0; i < this.length; ++i) {
output.push(cb(this[i], i, this));
}
return output;
};
Filter
It returns a new array containing only the elements that satisfy the given condition (i.e., for which the callback returns true). The original array remains unchanged.
const nums= [1, 2, 3, 4];
const greaterThan2 = nums.filter((num, i, arr) => num > 2);
console.log(greaterThan2); // [3, 4]
Implementation
Array.prototype.myFilter = function (cb) {
let output = [];
for (let i = 0; i < this.length; ++i) {
if (cb(this[i], i, this)) output.push(this[i]);
}
return output;
};
Reduce
It is probably the most complicated of all three. This method processes an arrayβs elements to produce a single output value.
const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10
Implementation
Array.prototype.myReduce = function (cb, initialValue) {
let accumulator = initialValue;
for (let i = 0; i < this.length; ++i) {
accumulator = accumulator!== undefined ? cb(accumulator, this[i], i, this) : this[i];
}
return accumulator;
};
Top comments (3)
Unfortunately, none of these implementations duplicate the JS built-in equivalents
Oh really? Thanks for pointing that out!
For interview, I think these implementations are sufficient. I also updated the post title to avoid any confusion.
They're not good polyfills either. Both
filter
andmap
are missing a parameter (thisValue
). Using these polyfills could easily break code.