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