How to get a sum of an array in Nodejs using foreach?

Sam

I have an array/schema called "plants",and populating on a webpage. I want to get the sum of plant rates(last item). how can i do that in Nodejs?

Below is the template showing plants table with the data from schema:

<% project.plants.forEach(function(plant){ %>
                  <tr>

                     <td class="td14" ><%= plant.noplant %></td>
                     <td class="td15" ><%= plant.plantname %></td>
                     <td class="td16" ><%= plant.planthrperday %></td>
                     <td class="td17" ><%= plant.plantnodays %></td>
                     <td class="td18" ><%= plant.planthrrate %></td>
                     <td class="td19" ><%= plant.plantdep %></td>
                     <td class="td20" ><%= plant.plantrate %></td>
                     <td class="td21"><a href=""><button type="button" class="btn btn-danger">Remove</button></a></td>

                   </tr>
                <% }); %>

The route handler:

    app.get("/myprojects/:id/cost", function(req,res){

    Project.findById(req.params.id).populate("labours materials tools plants others").exec(function(err, foundProject){
        if(err){
            console.log(err);
            }else{
          res.render("cost", {project: foundProject});   
        }

    });

  });
Farhan Tahir

You can do this in template as I did below by declaring a variable plantRateSum and adding plantrate to that variable on every iteration of forEach

<% var plantRateSum = 0;  %>

<% project.plants.forEach(function(plant){ %>
          <% plantRateSum += plant.plantrate %> 
           enter code here
                  <tr>

                     <td class="td14" ><%= plant.noplant %></td>
                     <td class="td15" ><%= plant.plantname %></td>
                     <td class="td16" ><%= plant.planthrperday %></td>
                     <td class="td17" ><%= plant.plantnodays %></td>
                     <td class="td18" ><%= plant.planthrrate %></td>
                     <td class="td19" ><%= plant.plantdep %></td>
                     <td class="td20" ><%= plant.plantrate %></td>
                     <td class="td21"><a href=""><button type="button" class="btn btn-danger">Remove</button></a></td>

                   </tr>
                <% }); %>

But this would not be a good approach instead you should send sum of plant rates to template from route handler using reduce method like below:

const plantRateSum = project.plants.reduce(function(sum, plant){
  return sum + plant.plantrate;
}, 0);

Now pass this plantRateSum to template.

In your route handler do this:

 app.get("/myprojects/:id/cost", function(req,res){
    Project.findById(req.params.id).populate("labours materials tools plants others").exec(function(err, foundProject){
      if (err) {
        console.log(err);
      } else {
        var plantRateSum = foundProject.plants.reduce(function(sum, plant){
          return sum + plant.plantrate;
        }, 0); 
        res.render("cost", {project: foundProject, plantRateSum:plantRateSum});   
      }
    });
  });

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to get sum of array in foreach in laravel 6

分類Dev

How to get the sum of number from an array of objects, using pure JS?

分類Dev

Using map() and forEach in NodeJS

分類Dev

PHP - How to get the sum of a multidimensional array?

分類Dev

How to loop array of objects using forEach?

分類Dev

Search for keywords in array and only get the matching elements in MongoDB using NodeJS

分類Dev

How to get column in 2-D array in java by Foreach loop?

分類Dev

how to get sum of int array field in projection in spring data mongodb

分類Dev

How to get a the sum of multiple arrays within an array of objects?

分類Dev

How to find sum objects inside an array using mongoose ,node ,

分類Dev

How to find sum objects inside an array using mongoose ,node ,

分類Dev

foreach with sql select get array

分類Dev

How to get the local timezone from the system using nodejs

分類Dev

dynamically generate array using .forEach()

分類Dev

get mongodb data to nodejs array?

分類Dev

sum of vlookup using array formula

分類Dev

Get cumulative sum with using group by

分類Dev

How to progressively sum a NumPy array

分類Dev

How to get total during a foreach

分類Dev

How to get a sum of some closures

分類Dev

How do I sum up all remaing amount after get max value from array?

分類Dev

Get the row with maximum sum in multidimensional array

分類Dev

How to take a value from nested array(json format) without using multiple foreach in php

分類Dev

How can i limit a Knockout foreach on an observable array to 5 at a time without using computed observables?

分類Dev

Create an array using forEach that has all the usernames

分類Dev

Write the sum of the values in to another file using Nodejs asynchronously

分類Dev

Sum of Array using for loop returning 0

分類Dev

How to get my data values sum() from past 24 hours in symfony using DQL?

分類Dev

How to get one line and Three colums in SQL (using the sum of costs for each menssenger)?

Related 関連記事

  1. 1

    How to get sum of array in foreach in laravel 6

  2. 2

    How to get the sum of number from an array of objects, using pure JS?

  3. 3

    Using map() and forEach in NodeJS

  4. 4

    PHP - How to get the sum of a multidimensional array?

  5. 5

    How to loop array of objects using forEach?

  6. 6

    Search for keywords in array and only get the matching elements in MongoDB using NodeJS

  7. 7

    How to get column in 2-D array in java by Foreach loop?

  8. 8

    how to get sum of int array field in projection in spring data mongodb

  9. 9

    How to get a the sum of multiple arrays within an array of objects?

  10. 10

    How to find sum objects inside an array using mongoose ,node ,

  11. 11

    How to find sum objects inside an array using mongoose ,node ,

  12. 12

    foreach with sql select get array

  13. 13

    How to get the local timezone from the system using nodejs

  14. 14

    dynamically generate array using .forEach()

  15. 15

    get mongodb data to nodejs array?

  16. 16

    sum of vlookup using array formula

  17. 17

    Get cumulative sum with using group by

  18. 18

    How to progressively sum a NumPy array

  19. 19

    How to get total during a foreach

  20. 20

    How to get a sum of some closures

  21. 21

    How do I sum up all remaing amount after get max value from array?

  22. 22

    Get the row with maximum sum in multidimensional array

  23. 23

    How to take a value from nested array(json format) without using multiple foreach in php

  24. 24

    How can i limit a Knockout foreach on an observable array to 5 at a time without using computed observables?

  25. 25

    Create an array using forEach that has all the usernames

  26. 26

    Write the sum of the values in to another file using Nodejs asynchronously

  27. 27

    Sum of Array using for loop returning 0

  28. 28

    How to get my data values sum() from past 24 hours in symfony using DQL?

  29. 29

    How to get one line and Three colums in SQL (using the sum of costs for each menssenger)?

ホットタグ

アーカイブ