What is the best way to compare and tally the occurrences of different property values from multiple objects stored in an array using JavaScript?

I've been grappling with counting occurrences of property values in an array containing multiple objects. I am currently working on developing an efficient method to iterate through these values. The structure of the array might resemble this:

var arr=[{1:["option1","option2"],2:["option2"],3:["option1"]},{1:["option2","option1"],2:["option1"],3:["option1"]}]

The array can consist of an unknown number of objects. Each object's property may also contain an unknown number of values stored in an array. All objects share the same properties, so I attempted to consolidate all properties with the first object. Although functional, it appears clunky and difficult to read. This approach feels unstable and unpredictable.

for(var firstobj=0,val=0,i=1,prop=1;arr.length>i;prop++,val++)
{
 if(prop>Object.getOwnPropertyNames(arr[i]).length)
{
    i++;
    prop=1;
}
else if(prop<Object.getOwnPropertyNames(arr[i]).length)
{
    i+0;
}
if(arr[i][prop].length<=val)
 {
  val=0;  
}
arr[firstobj][prop].push(arr[i][prop][val]);
}

In this code snippet, I attempt to manipulate the iteration by advancing to the next array index (i) only when the object's properties [prop] reach the end. I control the internal array iteration by resetting val to 0 if it exceeds the length of the array. Despite its functionality, I am dissatisfied with this piece of code. Perhaps you could offer alternative solutions to this issue. How can I organize multiple object values more effectively to later tally their occurrences for each property? Thank you.

Answer №1

Utilize nested loops for processing each layer of an array or object.

for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) { // exclude inherited properties from the prototype
            var arr2 = obj[key];
            for (var j = 0; j < arr2.length; j++) {
                // Perform actions with arr2[j]
            }
        }
    }
}

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

Parent and router-outlet in Angular 4 fashion

Suppose we are presented with the following code: <div class="container"> <div class="row"> <div class="col-sm-4 col-md-3"> <app-sidebar></app-sidebar> </div> <div class="c ...

Retrieve a string value in Next.JS without using quotation marks

Using .send rather than .json solved the problem, thank you I have an API in next.js and I need a response without Quote Marks. Currently, the response in the browser includes "value", but I only want value. This is my current endpoint: export ...

Troubleshooting VueJS, Electron, and Webpack integration with Hot Reload feature

I have been immersed in a new project that involves utilizing Electron, VueJS, and Webpack for HMR functionality. Unfortunately, I am encountering difficulties with the Hot Module Replacement feature not working as expected. Here is my current configurati ...

Error: The call stack has reached its maximum size limit

Below is a basic function utilizing webtorrent: addTorrent (opts) { return new Promise((resolve, reject) => { try { console.log('in try catch'); let torrent = wtClient.add(opts.source, (torrent) => { console.log(& ...

Make a request to the local API in a React Native mobile app by sending a GET request

Currently, I am working on a mobile application using React Native and utilizing SQL Server and NodeJS. The API for this project is located in my localhost. Upon running the application on an emulator, I encountered an issue when attempting to make a reque ...

Issue with MomentJS inBetween function consistently displaying incorrect results

I'm currently working on Vue Datatable and I have a specific requirement to search for records between two dates. I am using the moment.js library and the inBetween function to achieve this. Strangely, when I hardcode the dates, the function returns t ...

What is the best way to monitor useNavigate in React unit testing?

While working on my unit test, I encountered an issue where I am trying to test if useNavigate has been called after clicking on a button and if it has been called with the correct path. However, I am facing an error when attempting to spy on it. The error ...

Sending a text to a JavaScript function via the server side

Trying to send a string parameter from the server side to a JavaScript function for use in an AJAX method. The HTML is dynamically created on the server side, and the JavaScript function is triggered using the onclick property. However, there seems to be a ...

Extracting responseXML data specifically for CSS styling purposes

I am working on a simple XMLHttpRequest setup that fetches data from an xml file and displays it in a div on my webpage within a ul element: var requestData; if (window.XMLHttpRequest){ requestData = new XMLHttpRequest(); }else{ requestData = new ...

Misaligned tabs within Bootstrap Modal

Currently, I am working on creating a Bootstrap Modal that includes tabs for easy navigation within the modal. However, I have encountered an issue where the tabs are not aligned properly as shown in the image linked below: View Image Here This is the co ...

Exploring the advanced search capabilities of the _.where method in the underscore.js library

var x = { "name": "Example 1", "status": { "id": 1 } } var y = { "name": "Example 2", "status": { "id": 2 } } var z = [x, y]; var w = _.where(z, { "name": "Example 2", "status": { "id": 2 } }) ...

Efficient ways to determine the size of an array in Python

Hello fellow Python learners! I'm currently facing a challenge and would appreciate some guidance. I am trying to create an empty array at the beginning of my program with 'a' rows and 'b' columns. Although I attempted a solution, ...

Tips for displaying a script file from a remote server on your PHP page using AJAX

I'm currently working on executing a script from a remote server and displaying the output on an HTML page using AJAX for user visibility. I managed to do this successfully on my local server with up.sh and down.sh scripts. However, when attempting th ...

Using Node.js: Mimicking Keystrokes on the Server Side (Similar to a Macro)

I am currently working on a node.js script that is designed to replicate the functionality of sending keypresses, such as the up arrow or the "a" button. My ultimate goal is to create a clone of the popular game Twitch Plays Pokemon. Essentially, whenever ...

PHP JSON not working with Date Picker

My goal is to extract dates from a database and store them in a JSON format. These dates are intended to be used as unavailable dates in a datepicker. However, I am facing an issue where the datepicker is not displaying at all. checkDates.php ...

Having trouble assigning select values from my Angular JS controller

This specific scenario My attempt to change the selected value in the dropdown from the controller isn't working as expected, despite following guidance from various questions on this platform. The only unique aspect in my case is that I have a defau ...

In order to keep a div fixed at the top of the screen as you scroll, you can achieve this effect by utilizing CSS positioning. As the user scrolls down the page, the div

Can someone please help me figure out how to make a div element stay fixed on the screen as I scroll down the page? I've tried multiple solutions but nothing seems to be working. Any assistance would be greatly appreciated! I'm struggling with t ...

Implementing a button callback function using Aurelia binding

Is there a way to pass an array of custom button objects to a specific element? Here's an example: <my-component header="My Title" buttons.bind="[{icon: 'fa-plus', display: 'New', action: onNew}]"> </my-component> ...

Need a way to make the data from Python accessible in a HTML div through JavaScript?

X] Technologies in Use: 1] JavaScript 2] Jquery (currently using Jquery tab and Jquery datatable) 3] Python 4] Google App Engine Y] Issue Overview: 1] A JavaScript function connects to a Python class with the user's city and country values. 2] ...

What is the best way to add a trigonometric shape to a web page?

Currently, I am undertaking a project that requires the insertion of a large number of trigonometrical shapes into a webpage. To provide some context, I am working on the conversion of an ancient book into HTML format. The challenge lies in the fact that c ...