Count items inside array of objects

Tags: , ,



I am using this code to fetch 100 trending public repos on GitHub.

For every language, I calculated the The list of repos using the language, but I can’t calculate the number of repos using this language

part of my code

const api_url =
    "https://api.github.com/search/repositories?q=created:>30&sort=stars&order=desc&per_page=100";
  const response = await fetch(api_url);
  const data = await response.json();

  var urls = data.items
      .map((a) => ({
        language: a.language,
        url: a.url,
      }))
      .filter((el) => {
        return el.language != null;
      }),
    result = urls.reduce((r, { language, url }) => {
      match = r.find((item) => language in item);
      match ? match[language].push(url) : r.push({ [language]: [url] });

      return r;
    }, []);

This is sample of my output

[{
"Vala": [
"https://api.github.com/repos/p-e-w/finalterm"
]},
{
"Swift": [
"https://api.github.com/repos/louisdh/panelkit",
"https://api.github.com/repos/hyperoslo/Whisper",
]},
{
"C": [
"https://api.github.com/repos/wishstudio/flinux",
"https://api.github.com/repos/Sunzxyong/Tiny"
]}]

My desired output is to count the URLs of each language and append it to its corresponding language

Answer

Some changes:

  • reduce urls to an object because it’s faster to lookup entries than array.find and generally less complex.
  • take the object and generate an array with language, url list for that language, and count (which is just url list length).

const urls = [
  {language: "java", url: "url1"},
  {language: "java", url: "url2"},
  {language: "php", url: "url3"},
  {language: "javascript", url:"url4"},
  {language: "php", url: "url5"},
  {language: "java", url: "url6"}
];

result = Object.entries(
  urls.reduce((r, { language, url }) => {
    if (!r[language]) r[language] = [];
    r[language].push(url);
    return r;
  }, {})
).map(([language, urls]) => (
  {language, urls, count: urls.length}
));

console.log(result);


Source: stackoverflow