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?
asked Oct 1, 2020 at 12:46
Rahul Saini
9371 gold badge12 silver badges30 bronze badges
-
Please do basic research before asking.Heretic Monkey– Heretic Monkey2020年10月01日 12:49:04 +00:00Commented Oct 1, 2020 at 12:49
-
What is the hard part? Forking the prototype? Creating the sum? Something else?Teemu– Teemu2020年10月01日 12:49:54 +00:00Commented Oct 1, 2020 at 12:49
-
2Dupe hammer. OP wants to create a new function in Array prototype, not just sum all items in an array...kind user– kind user2020年10月01日 12:51:54 +00:00Commented Oct 1, 2020 at 12:51
2 Answers 2
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())
answered Oct 1, 2020 at 12:49
kind user
42k8 gold badges69 silver badges78 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Oct 1, 2020 at 12:50
Mamun
69k9 gold badges51 silver badges62 bronze badges
Comments
lang-js