DEV Community

Cover image for Javascript Polyfill Array.prototype.square #4
chandra penugonda
chandra penugonda

Posted on • Edited on

Javascript Polyfill Array.prototype.square #4

This problem was asked by ByteDance.

Implement a custom Array function, Array.prototype.square()

which creates a new array with the results of squaring every element within the array the .square() method is called on.

Examples

[-2].square(); // [4]
[1, 2, 3, 4].square(); // [1, 4, 9, 16]

Enter fullscreen mode Exit fullscreen mode

Notes

  • The original array should not be modified.
  • Assume that the array only contains numbers.

Solution

Array.prototype.square = function () {
  return this.map((num) => num * num);
};
Enter fullscreen mode Exit fullscreen mode
  • We utilize Array.prototype.map() to iterate over each element in the array, and return a new array with the squared value of each element.
  • The original array is not modified due to the use of map(), which creates a new array with the results of calling the provided function on every element

Top comments (0)