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?

Rahul Saini
  • 927
  • 1
  • 11
  • 28

2 Answers2

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())
kind user
  • 40,029
  • 7
  • 67
  • 77
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);
Mamun
  • 66,969
  • 9
  • 47
  • 59