Displaying elements of an array object using Javascript

I am currently working on counting the frequency of elements in an array using a for loop with arrays of objects. The code prints the correct output.

counts = {};
counter = 0;
counter_array = [50,50,0,200]; //this example array is dynamically filled

for (var x = 0, y = counter_array.length; x < y; x++) {
    counts[counter_array[x]] = (counts[counter_array[x]] || 0) + 1;
}

console.log('FREQUENCY: ',counts); //output should be FREQUENCY: {50:2, 0:1, 200:1}

Now, I have another array containing arrays:

holder_text_array = [["a",50,0],["b",0,0]]; //example of a dynamically filled array
var p = "a";
var i = 0;
while(i < holder_text_array.length){
    if (holder_text_array[i][0]==p) {
        var s = counts[holder_text_array[i][1]];
        console.log('Element: ', holder_text_array[i][1]); //outputs 50 when i = 0
        console.log('frequency: ',counts[s]); //prints undefined
        counter = counts[s];
    }
i++;
}

The array of arrays named "holder_text_array" contains elements whose frequencies I would like to obtain within this while loop. Can someone help me identify where my code may be incorrect?

Answer №1

The data is saved in variable s instead of counts[s]

You are currently logging counts[s] when the correct way should be using

var s = counts[holder_text_array[i][1]];

You already have the value from counts stored in s. Simply log the value of s

Other than that, the function is functioning properly!

counts = {};
counter = 0;
counter_array = [50,50,0,200]; //this is just for example, this array is filled dynamically

for (var x = 0, y = counter_array.length; x < y; x++) {
    counts[counter_array[x]] = (counts[counter_array[x]] || 0) + 1;
}

console.log('FREQUENCY: ',counts); //outputs FREQUENCY: {50:2, 0:1, 200:1}
holder_text_array = [["a",50,0],["b",0,0]]; //example of dynamically filled array
var p = "a";
var i = 0;
while(i < holder_text_array.length){
    if (holder_text_array[i][0]==p) {
        var s = counts[holder_text_array[i][1]];
        console.log('Element: ', holder_text_array[i][1]); //prints 50 for i = 0
        console.log('frequency: ', s); // CHANGED THIS TO JUST `s`
        counter = counts[s];
    }
i++;
}

Answer №2

One option is to implement a recursive solution where the count function is called again for arrays within the main array using the same counts object.

The final result will provide a breakdown of the frequency of each element in the array.

function getElementCounts(array, counts = {}) {
    for (let i = 0; i < array.length; i++) {
        const value = array[i];
        if (Array.isArray(value)) {
            getElementCounts(value, counts);
            continue;
        }
        if (!counts[value]) counts[value] = 0;
        counts[value]++;
    }
    return counts;
}

console.log(getElementCounts([["a", 50, 0], ["b", 0, 0]]));

Answer №3

After careful analysis, I was able to identify the root cause of the issue which lies in the initialization process. In order to resolve it, I made the necessary adjustments:

var s = counts[holder_text_array[i][1]];
counter = counts[s];

The revised code now looks like this:

var s = holder_text_array[i][1];
counter = counts[s];

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

How to get the clean URL in AngularJS without any parameters using $location

One issue I'm facing is related to the URL structure of my application. It currently looks like this: "http://host:port/mySystem?x.system" The addition of x.system in the URL was necessary due to a legacy application requirement, but now I need the U ...

Results from character array

Could someone please clarify the reason behind this unusual output? Why doesn't it display only one arr[b] every time? 123.in 2 QWERT YUIOP ASDFG HJKLZ XCVBN QWERT YUIOP ASDFG HJKLZ XCVBN Main.cpp int main() { int n; char arr[5][5]; if ...

Can you identify the transport protocol that serves as the foundation for XmlHttpRequest?

I'm interested in finding out if it's SOAP, plain HTTP, or something different. I tried looking up XmlHttpRequest on Wikipedia but couldn't find any information about it there. ...

Preserving the value of a function argument for future reference

I have a function called myFunction() that accepts one argument. My goal is to save this argument to a variable and be able to access it later. Here is what I am attempting to do: When a user performs an action, an event is passed as an argument to the m ...

Transform a button into an AngularJS directive

Is there a way to create a custom directive in HTML to represent a button? For example: <buy-button></buy-button> Here is the code that I would like to change: <md-button class="md-cornered" ng-disabled="0>=gains" ...

Ways to implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

"Oops, we hit a snag" notification appears when attempting to share on Facebook using the share dialog

I am currently integrating Django with Facebook for page sharing. Below is the code snippet I am using to form the URL: var link = 'https://www.facebook.com/dialog/feed?app_id=1234567890&display=popup&name=' + name + '&descripti ...

Angular and Bootstrap Popover: Maintain popover visibility while hovering over the popover container

For days, I've been struggling with a problem that's been driving me crazy. I need to display a popover with links when hovering over a button. The popover should stay open when the mouse is hovering over the button or the popover box. I'm ...

manipulating arrays output

Could someone explain to me the reasoning behind how this code functions? #include <stdio.h> int main() { int a[5] = {1,2,3,4,5}; int i; for(i=0;i<5;i++) { printf("%d,%d \n",i[a],i[a]++); } return 0; } The outp ...

Creating a 2D array containing all distinct combinations of numbers less than a specified maximum value for each cell, beginning at 1

Greetings and thank you for your attention. (my mathematical vocabulary in English is limited, so if you can suggest a better title for this question, feel free to edit and thank you for your assistance.) I am currently working on creating a function tha ...

Assistance Required in Turning Down Trade Requests on Steam That Involve Losing items

Currently, I have a code snippet from a Steam bot that processes incoming trade offers by accepting or declining them based on their state. However, my goal is to modify it in a way so that it automatically accepts trade offers where I receive items, but ...

Improved method for retrieving a subtask within a personalized grunt task?

As someone who is just starting out with Grunt and has only created a few custom grunt tasks, I've come up with what might be seen as an unconventional solution for traversing the initConfig to subtasks. My approach involves putting together a regex a ...

Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like: { "all": [ { "image":{ "URL":"img/img1.jpeg", ...

Running Javascript through Selenium with Python while using Tkinter for the GUI

Hey there! I am currently working on a project where I am developing a website using Selenium WebDriver integrated with a Tkinter GUI. In the GUI, I have an entry field and a button. When I enter a URL in the field and click the button, the web browser ope ...

The array within the document is unable to perform $push, $pull, and $inc operations simultaneously

In my collection, each document follows this format: { "_id": "57e81e0d5891000c99cc133b", "name": "service_name", "use": 8, "errors": [], } The errors field may contain objects like: { "e": { "error": "socket hang up" }, "d": "2016-10- ...

Executing a Knex RAW MySQL query to insert new records into a database table

As someone new to working with MySQL, I have previously used PSQL in a similar manner. However, the following code is generating an error. return await db .raw( `INSERT INTO users(firstName, lastName, email, ...

Is it possible to merge various jQuery setTimeout functions together?

I am currently using the following jQuery code for a specific task: setTimeout(function() { $("#ToDo1").removeClass("fa-spin fa-spinner"); $("#ToDo1").addClass("fa-check-square"); $("li:first").html("<i class='fa-li fa fa-check-square& ...

Creating elements with looping can be accomplished by using a combination of

Looking for assistance on looping through data displayed in a div tag using the code below: function GetDataFromServer() { var url = "http://bertho.web.id/curl/services21/DataReadNP.php"; JSONP.get(url, {}, function(response){ var listItem, container ...

Protecting against Cross-Site Request Forgery (CSRF) and Cross-S

When it comes to my application, I require clients to generate a unique token for themselves before making any requests to access server resources. However, this method alone does not fully protect against CSRF attacks. So, what are the most effective str ...

jQuery: automatic submission on pressing enter compared to the browser's autocomplete feature

Here is a JavaScript code snippet that automatically submits the form when the user presses the "enter" key: jQuery.fn.installDefaultButton = function() { $('form input, form select').live('keypress', function(e) { if ((e.which && ...