-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.

3
  • Chaining is where calling a function returns a function. You're asking about adding a method to arrays. Commented Oct 12, 2017 at 9:16
  • I believe you are looking for map Commented Oct 12, 2017 at 9:18
  • I know I could do it by writing a function like function multiply(arr){process each element of arr and return result } but that's not how I want it. Commented Oct 12, 2017 at 9:19

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This a great answer. It is what I was looking for. Array.prototype and String.prototype.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.