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?

David Cullen
  • 13,143
  • 4
  • 35
  • 60
Rahul Saini
  • 895
  • 1
  • 10
  • 23

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
  • 34,867
  • 6
  • 60
  • 74
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
  • 62,450
  • 9
  • 45
  • 52