Skip to main content

Arrays.map

The Array.prototype.map method creates a new array populated with the results of calling a provided function on every element in the calling array.

code

Array.prototype.myMap = function (callbackFn) {
var arr = [];
for (var i = 0; i < this.length; i++) {
arr.push(callbackFn(this[i], i, this));
}
return arr;
};

Explanation:

  1. Initialization:
  • var arr = []; initializes a new empty array to store the results.
  1. Loop through the array:
  • for (var i = 0; i < this.length; i++) { ... } loops through each element of the array.
  1. Callback Execution:
  • callbackFn(this[i], i, this) calls the provided function callbackFn with three arguments: - this[i]: the current element.
  • i: the index of the current element. this: the array being processed.
  1. Push Results:
  • arr.push(callbackFn(this[i], i, this)); stores the result of callbackFn in the new array.
  1. Return New Array:
  • return arr; returns the new array with the transformed elements.