Custom map, filter and reduce functions in Javascript


April 01, 2019

const values = [2, 3, 4, 7, 41, 22];
// Custom map
Array.prototype.customMap = function(cb) {
  for (var i = (this.length - 1); i >= 0; i--) {
    cb(this[i], i);
  }
}
console.log("Map")
const ma = values.customMap((val, index) => console.log(index, val))
// Custom filter
Array.prototype.customFilter = function(cb) {
  const filteredArray = [];
  for (var i = (this.length - 1); i >= 0; i--) {
    cb(this[i]) && filteredArray.push(this[i])
  }
  return filteredArray
}

const fa = values.customFilter(val => { return (val > 5) })
console.log("Filter", fa)
// Custom reduce
Array.prototype.customReduce = function( cb ) {
  let acc = 0;
  const arrLength = this.length;
  for (var i = 0; i < arrLength; i++) {
    acc = cb(acc, this[i], i, this);
  }
  return acc;
}

const ra = values.customReduce((acc, curVal, curInd, srcArr) => {
  return acc + curVal
});
console.log("Reduce", ra)

Subscribe to my newsletter


powered by TinyLetter and illustration from Lukaszadam

Girish Patil

Hi, My name is Girish Patil
I am a full stack developer @hashnode