Reputation: 174
I am trying to make a little nodejs ticker for calculating market cap. There are about 1500 entries. I want to loop through them, and sum up the values. Currently stuck on the loop
JSON URL
https://api.coinmarketcap.com/v1/ticker/?limit=10
Current Code
const https = require("https");
const url =
"https://api.coinmarketcap.com/v1/ticker/";
https.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
body = JSON.parse(body);
console.log(
`Coin: ${body[0].id} -`,
`Marketcap: ${body[0].market_cap_usd}`
);
//Loop through body results, sum up body[key].market_cap_usd
//console.log(total_sum)
});
});
Current Output
Coin: bitcoin - Marketcap: 149563018605
Any help would be greatly appreciated!
Upvotes: 0
Views: 35
Reputation: 1513
reduce
is your friend:
const https = require("https");
const url =
"https://api.coinmarketcap.com/v1/ticker/";
https.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
body = JSON.parse(body);
console.log(
`Coin: ${body[0].id} -`,
`Marketcap: ${body[0].market_cap_usd}`
);
const total_sum = body.reduce((sum, item) => sum + Number(item.market_cap_usd), 0)
console.log(total_sum)
});
});
Upvotes: 1