05-Aug-2022
.
Admin
Hi Friends,
Here, I will show you how to works how to find sum of all elements in list in node js. you will learn node.js get sum of all elements. I would like to share with you get sum of all elements in node js. step by step explain sun in array list in node js. Let's see bellow example node.js array list sum.
There are many ways to get a sum of elements in a list in node js. i will give you two examples using reduce() and for loop to sum of all elements of list in node js.
let's see below a simple example with output:
Install Node JS
This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:
mkdir my-app
cd my-app
npm init
Example: 1
index.js
// create array list
myArray = [1, 2, 3, 4];
sum = 0;
//sum of elements to myArray
for (let i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
console.log(sum);
Output:
10
Example: 2
index.js
// creating array list
arr = [4, 8, 7, 13, 12]
// using reduce function to find the sum
sum = arr.reduce(function (x, y) {
return x + y;
}, 0);
console.log("Sum using Reduce method: " + sum);
Output:
Sum using Reduce method: 44
I hope it can help you...
#Node JS