1

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.

2
  • What's the output and what do you expect it to be? Commented Feb 21, 2020 at 19:54
  • I expect it to be a number, value depends on the user, For eg. Dan Abramov, the stars count is 1427. The last time I tried.. I think I got a NaN. Commented Feb 21, 2020 at 20:03

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

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.