An array containing objects with keys represented as arrays is required to tally the occurrences of each value within the array that acts as a key

Trying to identify the top body locations using a dataset structured like this... the dataset consists of an array of objects, each containing an array called bodyLocations which I need to analyze to determine the most frequently appearing locations such as r-ovary, l-ovary etc.

My current approach involves concatenating all body locations arrays together and then counting them. However, I have a feeling there might be a more efficient way to accomplish this. Should I delegate this task to MongoDB, where the data originates from, or continue handling it on my server? Any suggestions on the best strategy for tackling this issue?

Data snapshot for the week:  [
    {
        bodyLocations: [ 'r-ovary', 'l-ovary', 'l-leg', 'r-leg', 'head' ],
        typePain: [ 'aching', 'fatigue' ],
        _id: 6074d376215c0c033aa41aef,
        postedBy: 6060ca6b8dbe9d02e4ad1063,
        created: '2021-04-12',
        symptomDate: 2021-04-12T00:00:00.000Z,
        painlevel: 6,
        __v: 0
    },
    {
        bodyLocations: [ 'r-ovary', 'uterus' ],
        typePain: [ 'fatigue', 'twisting', 'radiating' ],
        _id: 6074dd89ebabd8034831786a,
        postedBy: 6060ca6b8dbe9d02e4ad1063,
        created: '2021-04-12',
        symptomDate: 2021-04-12T00:00:00.000Z,
        painlevel: 9,
        __v: 0
    }

Answer №1

The data in bigArr is not being collected here:

 el.bodyLocations.push(bigArr)

Instead, it adds a reference to an (empty) bigArr to the bodyLocations property of each object.

If you want to track occurrences frequency, follow these steps:

const freq = {};
for (let {bodyLocations} of symptomDataWeek) {
    for (let location of bodyLocations) 
        freq[location] = (freq[location] || 0) + 1; 
}

To find the location with the highest frequency:

const maxFreq = Math.max(...Object.values(freq));
const location = Object.keys(freq).find(location => freq[location] === maxFreq);

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

Is there a way for me to generate a tab that shows content when hovered over?

Is it possible to create a tab that displays a vertical list of redirections when the mouse hovers over it, and hides when the mouse is moved away? This seems like a challenging task. Can someone guide me on how to achieve this, especially if it involves ...

Trouble with AngularJS: Default values not being set by ng-model

In this code snippet, I have set up ng-model to pass filter into my function and retrieve all user selections. Initially, I believed it could also be used to prefill or default the data. However, I am facing issues with this approach. Here is an excerpt fr ...

Guide to setting up an object array in JavaScript with unique child elements and no duplicate values

I have an array that looks like this: sampleArray = ["x", "y", "z". "a.b", "a.b.c", "a.b.d", "a.e.f", "a.e.g"] However, I am aiming to transform it into the following structure, or something similar to it: newArray: [ { "x": [] }, ...

10, 9, 8... Preparing to forward you to the next page

Hello there, I am currently working on a webpage that has a 10 second delay before redirecting. var timer = window.setTimeout('redirect(strUrl)', 11000); The function redirect(strUrl) simply changes the document's location. I think it w ...

Step-by-step guide to uploading text and image simultaneously through AJAX

I encountered a challenge while attempting to create a signup form that requires user data and an image upload. Despite my efforts, I couldn't achieve the desired outcome with the provided code snippet. I've explored similar questions but none ha ...

Creating a redirect page without triggering a preventDefault() function:

One issue arises when I include e.preventDefault and it doesn't redirect to homeadmin.php after a successful login, even though the ajax call is successful and there are no validation errors. The second problem is that in order to display error messa ...

Can one operate multiple shards on various remote instances without using a replica set?

I have implemented a sharding setup on CentOS using 64-bit MongoDB v2.0. Initially, I set it up on a single instance with 2 shards, 1 config server, and 1 mongos, which was working fine. However, when I tried splitting the components onto three separate in ...

Converting CSDL format into JSON data structure

Is there a way to convert data retrieved in CSDL format from an Oracle DB into JSON format using NODE JS? export async function getRecepFarma(req: Request, res: Response): Promise<Response> { const conn = await connect(); const result = await ...

Searching for a specific key within a nested collection using $lookup

Assume I am in possession of the following collections: linkedDetails: { _id:ObjectId("1234avshjd"), book_id:ObjectId("16262ahahha"), author_id:ObjectId("127hjajaj") } { _id:ObjectId("223ahha78"), book_id:Obje ...

What is the code to retrieve all _id values within an array in MongoDB?

I currently possess the following assortment: { "_id" : ObjectId("5acdb95d5ea63a27c1facf92"), "venue" : ObjectId("5acdb95d5ea63a27c1facf8c"), "author" : ObjectId("5ac8ba3582c2345af70d4658"), } { "_id" : ObjectId("5acdb95d5ea63a27c1facf93") ...

What is the best way to query the ng-model table using xpath in Selenium with Java?

I'm having trouble finding a table from DOCTYPE Html using xpath or className in Selenium/java. I can't seem to locate the locator. How can I retrieve the table using selenium java? Neither of the following paths are effective. You can view a sc ...

Creating a network of lists by combining multiple arrays

I'm currently working on generating a comprehensive list of all possible combinations of multiple arrays. While I have experience in Matlab and understand loops and basic coding principles, I'm unsure of the most efficient method to compile these ...

What could be causing the Access-Control-Allow-Origin error to appear when attempting to access a page using ajax?

As I attempt to utilize Ajax to retrieve data from my website using a script that should be able to execute from any location, the Ajax code within my script is structured like this: var ajax = new XMLHttpRequest(); ajax.open('GET', 'http:/ ...

JavaScript Function for Shuffling an Array

Looking for advice on optimizing a function I'm developing. My goal is to: Double the frequency of numbers in an array Randomize the location of the values in the array. For instance: Imagine I have an array. [0,1,2,3] First, I need to dupl ...

Firefox detects video interference from webcam

Take a look at this test code: <!doctype html> <html> <body> <video id="v1" autoplay="autoplay"></video> <script> navigator._getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserM ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

How can you toggle the visibility of a React component based on the user's device browser?

Seeking a solution to dynamically hide/show a component in a React/Nextjs/tailwind webapp based on the user's device type (e.g. desktop vs tablet vs mobile) due to differences in available keyboard keys (e.g. tab key not present on tablets and mobile ...

What is the best way to clear the values of multiple chosen-select boxes in one go?

I am encountering an issue while using a chosen-select plugin. I have multiple select boxes created with JavaScript code. My goal is to reset all select boxes when I change the class to "default-chosen", but instead of displaying my message "not chosen," i ...

The functionality of Body Parser has been phased out

I'm facing an issue with using Bodyparser in my code as the editor itself cuts off the code and mentions that body-parser is deprecated. I've attempted to use some alternative codes found online, but none of them seem to be working. Here's a ...

Integration of AngularJS and Node.js using ExpressJS

Currently, I am working on developing an app using Node.js with Express and AngularJS. I have a query regarding whether it is feasible to delegate all landing requests to AngularJS while solely utilizing Node.js for APIs. This implies that all routes defi ...