How to Find Sum of All Elements in List in Node JS?
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
- How to Install Node Js and NPM Ubuntu?
- How to used Google ReCaptcha V3 in Node Js Express?
- How to Send Email with Attachment in Node js?
- How to Insert Data from Form into MySQL Database using Node js Express?
- Install Node Js and NPM Ubuntu 18.04/20.04/22.04 Tutorial
- How to Delete Data by id into MongoDB in Node JS?
- Install Node.js 16/17/18 on CentOS 8 Tutorial
- How to Upload File in MongoDB using Node js Express?