Calculating distinct values within a single key in an object

My goal is to track the occurrences of four specific string values within the same key.

The issue lies in my struggle with adding multiple counters. While the first counter successfully tracks the initial condition, subsequent conditions within the if/else statement impede the proper counting of all conditions. This data is sourced from a Promise.all that includes various URLs.

Below is my code snippet:

 const urls = [
  'https://api.github.com/users/TylerP33/repos?page=1',
  'https://api.github.com/users/TylerP33/repos?page=2',
  // more URLS here...
];

function getLanguages() {
  return Promise.all(urls.map(url =>
    fetch(`${url}`)
    .then(response => response.json())
    .then(obj => obj.forEach(function(val) {
      let rubyCounter = 0;
      let cssCounter = 0;
      let htmlCounter = 0;
      let jsCounter = 0;
      
      if (val.language === "Ruby") {
        rubyCounter++;
        console.log(rubyCounter);
      }

    })))
  )
}

getLanguages();
 

rubyCounter correctly displays 235, but introducing additional conditions seems to disrupt the counting process due to the true/false conditions affecting the same key. I may be overlooking something obvious and would appreciate your input on this matter.

Thank you in advance.

Answer №1

When looking at this code snippet, it becomes apparent that the variable rubyCounter will consistently have the value of 1 once logged because the counter is always initialized within the callback function.

To resolve this issue, it is necessary to relocate the definition of the counters to the root of the getLanguages function.

Instead of using multiple variables for each counter, a better approach would be to utilize an Object where each language to count corresponds to a property.

const urls = [
  'https://api.github.com/users/TylerP33/repos?page=1',
  // Additional URLs omitted for brevity
]

function getLanguages() {
  let counter = {
    ruby: 0,
    html: 0
  }

  return Promise.all(urls.map(url =>
      fetch(`${url}`)
      .then(response => response.json())
      .then(obj => obj.forEach(function(val) {
        if (val.language === "Ruby") {
          counter.ruby++;
        } else if (val.language === "HTML") {
          counter.html++;
        }
      }))
    ))
    .then(() => {
      console.dir(counter)
    })
}

getLanguages();

If counting all languages is the goal, there is an even simpler solution:

const urls = [
  'https://api.github.com/users/TylerP33/repos?page=1',
  // Additional URLs omitted for brevity
]

function getLanguages() {
  let counter = {}

  return Promise.all(urls.map(url =>
      fetch(`${url}`)
      .then(response => response.json())
      .then(obj => obj.forEach(function(val) {
        if( val.language ) {
          counter[val.language] = counter[val.language] || 0
          counter[val.language]++
        }
      }))
    ))
    .then(() => {
      console.dir(counter)
    })
}

getLanguages();

Answer №2

If you want to test this out, give it a try:

const urls = [
            'https://api.github.com/users/KatieSullivan/repos?page=1',
            'https://api.github.com/users/KatieSullivan/repos?page=2'
        ]

        var languageCounters = {};
        function retrieveLanguages() {
            return Promise.all(urls.map(url => {
                fetch(`${url}`)
                    .then(response => response.json())
                    .then(json => json.forEach(function (val) {
                        if (!languageCounters[val.language])
                            languageCounters[val.language] = 0;

                        languageCounters[val.language]++;
                    }))
                    .then(() => {
                        console.log(languageCounters);
                    });
            }));
        }

        retrieveLanguages();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Space between flex content and border increases on hover and focus effects

My code can be found at this link: https://jsfiddle.net/walshgiarrusso/dmp4c5f3/5/ Code Snippet in HTML <body onload="resize(); resizeEnd();"> <div style="margin: 0% 13.85%; width 72.3%; border-bottom:1px solid gray;"><spanstyle="visibilit ...

Changing the CSS class of the Bootstrap datetime picker when selecting the year

Is there a way to change the CSS style of the Bootstrap datetime picker control so that when selecting years, the color changes from blue to red? I attempted to do this with the following code: .selectYear { background-color:red!important; } However ...

Why is adding a div to Facebook posts using JQuery failing due to dynamic loading?

I have been experimenting with the mouseover feature to enhance a Facebook group by adding additional content. Upon testing the DIV class, I realized that after the initial 10 or so instances of DIVs with the class storyInnerWrapper, the text stopped being ...

Tips on leveraging state values within the makeStyles function in Material UI React

I'm in the process of building a Webpage and incorporating Material UI for the Components. Here's the code: import { makeStyles, Typography } from "@material-ui/core"; const useStyles = makeStyles((theme) => ({ container: { ...

Identifying tick markers in the event loop of JavaScript and Node.js

Is there a way to determine if a function is called in the current tick or if it will be called in the next tick of Node.js event loop? For instance: function exampleFunction(callback){ // we can call callback synchronously callback(); // or we c ...

Exploring the firestore section with vuefire for seamless access to methods

I am attempting to access a method in the firestore section of vuefire, but encountering the following error: vue-router.esm.js?8c4f:2257 TypeError: Cannot read property 'messagesWith' of undefined at eval (Chat.vue?62f3:214) This is the lin ...

Troubleshooting: Issues with AngularJS $route.reload() functionality

I have an angular app and I'm attempting to refresh the page. I've tried using $route.reload() as recommended in multiple posts, but I can't seem to get it to work (Chrome is showing me an error). Here's my controller: var app = angula ...

Inserting a line break in real-time within a JSX statement

Currently working on a React application that retrieves song lyrics from an API. The API provides me with a lyrics_body attribute as a string, which I use to showcase the lyrics on the webpage. However, when React renders it, the format is not ideal becau ...

Leveraging Node.js to establish a connection between two pug files

Recently, I decided to delve into the world of pug and JavaScript. However, I seem to be facing a small issue that I can't quite figure out on my own. My project involves creating multiple .pug files with various text content that I can navigate betwe ...

Using AngularJS to Nest ng-view within ng-repeat

I have a collection of items. Each item has buttons to display its details and comments within this ng-view section. It is necessary for the user to view all available product details on one page, for example. Below is the HTML list: <div ng-controll ...

Exploring the Depths of NodeJS X-Ray Web-Scraper: Uncovering Hidden Gems within Sub Pages

Currently, I am attempting to scrape content using the node.js x-ray scraping framework. While I have successfully retrieved data from a single page, I am struggling with navigating through links and extracting content from subpages simultaneously. Althou ...

Is it feasible to activate an action on a click of a Vimeo video?

Is there a way to activate an event by clicking if a video is set with background=1 and has no controls? This particular video is from Vimeo, using a plus account which allows for setting background=1. The scenario involves a Vimeo video playing on loop ...

JavaScript Function to Convert JSON Data into an Excel File Download

I am looking for help with converting JSON data received from an AJAX POST Request into an Excel file (not CSV) for download on a button click. The JSON Data may contain blank values and missing fields for each JSON row. I have attempted to achieve this o ...

Rails implementation of AJAX pagination

Here is the jquery code I am using: $(function() { $(".pagination span.page a").click(function (){ $.get(this.href, null, alert("The pagination link was clicked" + this.href), "script"); return false; }); }); The alert pops up, confirming that ...

Encountering a React JS error with Admin on Rest while making an API request

When making an API call (GET) with React.js using Admin on Rest, I encountered an issue. The server returns data when calling localhost:5001/cities, but there seems to be an error on the client side as indicated by the browser log: failure.js:18 Error: Th ...

In order to display the new component upon the first click in React, my button requires a double click

I have a project that utilizes the open Trivia API to fetch data. I've completed the development and everything appears to be working well so far. However, there's a bug where upon initially rendering the app, the first time I click the button to ...

Turn the image inside the div with the nth-child selector into a clickable link

I'm currently facing a challenge on my Squarespace website where I need to add individual links to various images using jQuery. The issue is that these images do not have a shared class, and unfortunately, I am limited to adding custom CSS or JavaScri ...

Unable to access static library Java Script file path using NSBundle

I have integrated a static compiled library into my project, which includes a JavaScript resource. At a specific event in my app, I need to execute the JavaScript file from this library. However, I am facing an issue where the path to the JS file appears ...

How should we structure our JavaScript code: MVC or self-rendering components?

I'm in the process of developing a highly JS-centric web application. The bulk of the work is being carried out on the client side, with occasional syncing to the server using AJAX and XMPP. This is my first venture into creating something of this ma ...

Reverting Vue Draggable Components to Their Original Position Upon Dropping Them

In my Vue 3 project, I'm implementing vuedraggable to enable element reordering within an expansion panel. However, I've encountered an issue where the dragged elements revert to their original positions upon release. This behavior suggests that ...