Reputation: 45
I am trying to get the total 'stargazers_count' from a particular user's github repo. This code, using 'for' loop is working. But I would like to use 'reduce'. I am posting what I tried. Can someone point to me where I am wrong? The JSON can be viewed with this url,using your github username:
https://api.github.com/users/${your username}/repos
This is the working code using for loop:
axios.get(response.data.repos_url)
.then((res) => {
let starCount = 0;
for(let i=0; i<res.data.length; i++) // find out the total number of github stars
{
starCount += res.data[i].stargazers_count;
}
response.data.NoOfStars = starCount; // add the total stars as a property in response object
This is what I tried with 'reduce':
axios.get(response.data.repos_url)
.then((res) => {
let starCount = 0;
const reducer = (acc, currVal) => acc + currVal.stargazers_count;
arr = res.data;
starCount = arr.reduce(reducer);
This did not work. If I can get a brief explanation of where and why I am wrong, it will be helpful.
Upvotes: 1
Views: 67
Reputation: 28196
You need to provide a starting value for your accumulator, otherwise reduce will assume that the first array element is the starting value and this would lead to a NaN
result.
starCount = arr.reduce(reducer,0);
Upvotes: 1