1

I'm trying to implement this code:

const a = [1, 2, 3, 4, 5];
a.multiply();
console.log(a); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]

The result array needs to be concatenated at the end of the original array. I'm using the following code but it returns only the array with the values multiplied:

Array.prototype.multiply = function() {
    return this.map(function(item){return item * item})
}
a.multiply();
console.log(a); //[1, 4, 9, 16, 25]

Can anyone help me please?

1
  • 1
    note that it's generally frowned upon to modify built-in object prototypes Commented Nov 16, 2018 at 20:19

4 Answers 4

3

You could push the items of mapping to this.

Array.prototype.multiply = function () {
    this.push(...this.map(v => v * v)); // push spreaded values
    return this;                        // allow fluent interface
};

var a = [1, 2, 3, 4, 5];

a.multiply();

console.log(a);

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

Comments

1

Pardon me for asking but why mutate the array? You can decorate the Array prototype with functions which simply return the result you need. Mutating the input/state has its disadvantages.

An approach where you do not mutate the array would be something like this:

Array.prototype.multiplyAll = function() {
  return this.reduce((r,c) => r * c)
}
Array.prototype.multiplyEach = function() {
  return this.map(x => x * x)
}

var a = [1, 2, 3, 4, 5];

console.log(a.multiplyAll());
console.log(a.multiplyEach());

In general the recommended approach is not to decorate the prototypes of the build in Objects but to have a utility of pure functions with which you work with.

Comments

0

You can use "Array.concat" and "Array.map" like below

const a = [1, 2, 3, 4, 5];

// for direct method
function multiply() {
  return a.concat(a.map(d => d * d))
}

console.log(multiply(a));

// for prototype method
Array.prototype.multiply = function() {
    Object.assign(this, this.concat(this.map(d => d * d)))
}

a.multiply()

console.log(a)

Comments

0

If you're coding to the ES6 spec you can use spread syntax in conjunction with Array.prototype.map method to achieve this. I re-named the method to pushSquared since I thought it made more sense.

Array.prototype.pushSquared = function() {
  Object.assign(this, [...this, ...this.map(n => n * n)]);
}

var a = [1, 2, 3, 4, 5];
a.pushSquared()
console.log(a);

2 Comments

Though a seemingly clean solution, it's not changing a as asked in OP
@NitishNarang - You are correct. I updated the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.