-2

I'm not sure the question title is right. Let's say I have:

var myArray=[12, 1, 25];

I want to write a function such as the following "multiply" function so that I can:

var newArray = myArray.multiply(7)

and the result would be:

newArray=[12*7, 1*7, 25*7]

But I'm not referring only to an array. Initial variable could be a string to do something with.

CristianC
  • 303
  • 3
  • 11

1 Answers1

2

You can achieve this by adding a multiply function to the prototype of Array.

See the code below.

var myArray=[12, 1, 25];

Array.prototype.multiply = function(arg) {
  return this.map(item => item*arg);
}

var newArr = myArray.multiply(7);

console.log(newArr);
Anurag Singh Bisht
  • 2,683
  • 4
  • 20
  • 26