Home > Web Front-end > JS Tutorial > Polyfill for Map, Filter, and Reduce Methods in Javascript

Polyfill for Map, Filter, and Reduce Methods in Javascript

王林
Release: 2024-08-16 06:18:12
Original
695 people have browsed it

Polyfill for Map, Filter, and Reduce Methods in Javascript

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]
Copy after login

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;
};

Copy after login

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]
Copy after login

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;
};
Copy after login

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
Copy after login

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;
};
Copy after login

The above is the detailed content of Polyfill for Map, Filter, and Reduce Methods in Javascript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template