0

I have a for loop in my script that loops through a set of markerNodes results. I was wondering, how easy is it to create a total variable that adds up the integer value in amount & outputs at the end?

for (var i = 0; i < markerNodes.length; i++) {
   var name = markerNodes[i].getAttribute("name");
   var address = markerNodes[i].getAttribute("address");
   var amount = markerNodes[i].getAttribute("amount");
   var distance = parseFloat(markerNodes[i].getAttribute("distance"));
   var latlng = new google.maps.LatLng(
        parseFloat(markerNodes[i].getAttribute("lat")),
        parseFloat(markerNodes[i].getAttribute("lng")));
   createOption(name, distance, i);
   createMarker(latlng, name, address, total);
   bounds.extend(latlng);
}
0

2 Answers 2

2

Quite easy to add

var total = 0;
for (var i = 0; i < markerNodes.length; i++) {
   var name = markerNodes[i].getAttribute("name");
   var address = markerNodes[i].getAttribute("address");
   var amount = markerNodes[i].getAttribute("amount");

   total += parseFloat(amount);

   var distance = parseFloat(markerNodes[i].getAttribute("distance"));
   var latlng = new google.maps.LatLng(
        parseFloat(markerNodes[i].getAttribute("lat")),
        parseFloat(markerNodes[i].getAttribute("lng")));
   createOption(name, distance, i);
   createMarker(latlng, name, address, total);
   bounds.extend(latlng);
}

console.log(total);
Sign up to request clarification or add additional context in comments.

9 Comments

Then see the comment behind the line, use parseFloat(amount) @michaelmcgurk
Edited it in the answer @michaelmcgurk
No problem, happy to help. @michaelmcgurk
Sure, create an element e.g. with an id: <span id="totalTarget"></span> somewhere on your page, and replace console.log() with document.getElementById("totalTarget").innerHTML = total; @michaelmcgurk
Welcome again @michaelmcgurk
|
0

This is another approach. (By using Array.reduce)

var total = Array.prototype.reduce.call(
   markerNodes, 
   (prev, cur) => prev + Number(cur.getAttribute("amount")), 
   0
);

1 Comment

true in isolation but this is redundant iteration in the case that you already have a for loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.