1

This is a part from my json file

     {
      "articles": [
        {
          "rank": "1",
          "title": "Harvard University",
          "country": "USA",
          "score": "100.00"
        },
        {
          "rank": "3",
          "title": "Massachusetts Institute of Technology",
          "country": "USA",
          "score": "97.12"
        },
        {
          "rank": "5",
          "title": "University of Oxford",
          "country": "United Kingdom",
          "score": "95.39"
        },
        {
          "rank": "36",
          "title": "École Polytechnique",
          "country": "France",
          "score": "59.09", 
        },
        {
          "rank": "904",
          "title": "University of Basilicata",
          "country": "Italy",
          "score": "44.31",
        }
        ]
    }

I want to count the number of same countries with JS function for making google charts. I need a result like this: country:{"USA" : 57,"Japan" : 23,"United Kingdom" : 38,"

And another function which will return the number of univercities whose scores are more than 80 and less than 80 , like this: score:{"morethan80" : 195,"lessthan80" : 805,"

Karen
  • 11
  • 2
  • 3
    You should show your efforts and some code you wrote. – Luca De Nardi Nov 03 '17 at 16:14
  • What is the first part you have trouble with? For example, are you able to import your JSON file into a variable that can be accessed by your code? Are you able to write code that iterates over each article element of the variable? It's not good to put the whole problem up and ask the community how to solve it for you. – Erik Hermansen Nov 03 '17 at 16:45

1 Answers1

3

What you have to do is to loop through your map and check wether it matches your condition and if so, increment it.

Typically, reduce takes an array in input and output whatever you want: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

const output = data.articles.reduce(
  (result, article) => ({
    country: {
      ...result.country,
      [article.country]: result[article.country] ? result[article.country] + 1 : 1,
    },
    score: {
      morethan80: parseInt(article.score) >= 80 ? result.morethan80 + 1 : result.morethan80,
      lessthan80: parseInt(article.score) < 80 ? result.lessthan80 + 1 : result.lessthan80,
    }
  }),
  { country: {}, score: { morethan80: 0, lessthan80: 0 }}
);

Tell me if you need more details on the answer.

yuantonito
  • 1,274
  • 8
  • 17