0

we have an array, we have to find the sum of all the elements in the array.

let a = [1, 3, 2, 0];

console.log(a.add());  ==> 6

How to implement add function please can you help me?

3
  • Please do basic research before asking. Commented Oct 1, 2020 at 12:49
  • What is the hard part? Forking the prototype? Creating the sum? Something else? Commented Oct 1, 2020 at 12:49
  • 2
    Dupe hammer. OP wants to create a new function in Array prototype, not just sum all items in an array... Commented Oct 1, 2020 at 12:51

2 Answers 2

4

There's no such function in Array prototype as add. You would have to create it.

Note: keep in mind that it's not recommended to modify the prototypes which may cause issues such as overwriting existing functions.

const a = [1, 3, 2, 0];
Array.prototype.add = function() {
   return this.reduce((a, b) => a + b, 0);
}

console.log(a.add())

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

Comments

1

You can try using Array.prototype.reduce():

let a = [1, 3, 2, 0];
var total = a.reduce((a,c) => a+c, 0);
console.log(total);

Comments

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.