Ways to determine the occurrence rate of a specific value within a collection of dictionaries?

Consider the array of dictionaries below:

var dictionary_demo = [
                         [
                            {country: "georgia", value: sunny},
                            {country: "france", value: rainy}
                         ],
                         [
                            {country: "georgia", value: sunny},
                            {country: "france", value: gloomy}
                         ],
                         [
                            {country: "georgia", value: rainy},
                            {country: "france", value: dry}
                         ]
                      ]

I'm trying to find out how many times each weather condition occurs in each country. Here's the desired output:

In Georgia: Sunny occurs twice and Rainy occurs once.

In France: Rainy occurs once, Gloomy occurs once, and Dry occurs once.

Answer №1

Utilizing an array of arrays (JS term for a dictionary in JS is actually an array), you can efficiently employ the flatMap function to extract all values from the inner arrays and merge them into the main array. Subsequently, you have the ability to loop through the flattened array and gather the desired values.

In this particular scenario, I would opt for utilizing the array.reduce method to convert the resultant flattened array into an object where each country has a specific key associated with it. This key corresponds to another object containing keys representing different weather types and their respective frequency of occurrence.

var dictionary_demo = [
                         [
                            {country: "georgia", value: "sunny"},
                            {country: "france", value: "rainy"}
                         ],
                         [
                            {country: "georgia", value: "sunny"},
                            {country: "france", value: "gloomy"}
                         ],
                         [
                            {country: "georgia", value: "rainy"},
                            {country: "france", value: "dry"}
                         ]
                      ]

function weatherFrequency(arr) {
  // Flatten the given array
  const flatArr = arr.flatMap(a => a)

  // Use the flattened array to generate frequencies for each value
  const sortedArr = flatArr.reduce((accum, { country, value }) => {

    // Check for the existence of the key, add if absent
    if (!accum[country]) accum[country] = {}

    // Determine frequency of weather type occurrence within a country
    accum[country][value] ? accum[country][value] += 1 : accum[country][value] = 1

    // Return accumulator for next iteration of `reduce`
    return accum
  }, {})
  return sortedArr
}

// Verify the resulting object obtained from the `reduce` operation
console.log(weatherFrequency(dictionary_demo))

// Construct a string containing the desired values
const countryWeather = weatherFrequency(dictionary_demo)

// Implement string interpolation to access required information
console.log(`In Georgia: sunny occurs ${countryWeather.georgia.sunny} times, while rainy occurs ${countryWeather.georgia.rainy} time`)

``

Answer №2

var dictionary_example = [
   [
      {country: "germany", condition: "cloudy"},
      {country: "italy", condition: "sunny"}
   ],
   [
      {country: "germany", condition: "windy"},
      {country: "italy", condition: "rainy"}
   ],
   [
      {country: "germany", condition: "snowy"},
      {country: "italy", condition: "foggy"}
   ]
]

var result = dictionary_example.reduce(function(accumulator, element){
    
    return accumulator.concat(element);

},[]).reduce(function(accumulator, element){

    if(!accumulator[element.country])
        accumulator[element.country] = {[element.condition]: 1};
    else
        accumulator[element.country][element.condition] = (accumulator[element.country][element.condition] ||  0) + 1;

    return accumulator;
    
}, {});

console.log(result)

Answer №3

When dealing with arrays of arrays, you have the option to flatten those arrays using a depth of 2. Following that, you can leverage the Array.prototype.reduce function to construct the desired output.

const arr = [   [      {country: "georgia", value: "sunny"},      {country: "france", value: "rainy"}   ],   [      {country: "georgia", value: "sunny"},      {country: "france", value: "gloomy"}   ],   [      {country: "georgia", value: "rainy"},      {country: "france", value: "dry"}   ]];
const result = arr.flat(2).reduce((a, {country, value}) => {
  const current = (a[country] ?? (a[country] = {[value]: 0}));
  a[country][value] = (a[country][value] ?? 0) + 1;
  return a;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

When outputting the $http response in the console, Angular displays null instead of the expected result,

I have encountered a peculiar issue with my local webservice developed using Spring. Everything seems to be functioning correctly when accessing it through the browser or Postman, but for some reason, when attempting a simple GET method with Angular/Ionic, ...

What could be the reason for the malfunction of the select (mongoose query)?

I'm trying to retrieve a User's highest score post. To accomplish this, I am querying the Post model and looking for posts where their user._id matches the author in the post. Everything is functioning correctly in this regard. However, my goal ...

When implementing dynatable with Meteor, the outcomes may vary between the demonstration in a fiddle and the actual application

Here is the fiddle I created for this question: https://jsfiddle.net/ereday/82wzwem8/2/ In the fiddle, you'll notice that the table header has a green background. Now, let me share the code snippet from my meteor project: simple-todos.html <head ...

Error: It appears that there is an issue with asynchronous operations causing a TypeError when trying to read the 'source' property of an undefined

As I delve into the world of JavaScript, I've decided to create my own ecommerce shop. However, as I attempt to preview the page locally, a frustrating error greets me: TypeError: Cannot read properties of undefined (reading 'source') Let&a ...

How to remove an event listener when e.target points to a hyperlink

element, I encountered an issue using a slideshow component sourced from our components library. This component receives swipe events from a utility function that is initialized upon mounting. The problem arose while testing on a mobile phone - tapping a ...

How can we control the timing of elements displaying on a web page in Javascript?

I've been attempting to implement a scrolling feature on my webpage using JavaScript, but whenever I run it, the content appears all at once instead of scrolling. The $("#Menu").html('') function doesn't seem to clear the screen properl ...

Firebase scheduled function continues to encounter a persistent issue with an "UNAUTHENTICATED" error being consistently thrown

I have created a firebase-function that is scheduled to retrieve data from an external API source and save it in Firestore. const functions = require("firebase-functions"); const admin = require("firebase-admin"); const { default: Axios ...

Tips for extracting and mapping a sub array from the category response JSON using SWR with MongoDB in a Next.js (Node.js) environment

Can anyone assist me with reading and mapping arrays inside JSON? Using Hook (useSWR / useCategories): import useSWR from "swr" const fetcher = (...args) => fetch(...args).then(res => res.json()) function useCategories () { const { data, erro ...

What strategies can I employ to optimize this code in RXJS and Angular?

Is it possible to streamline these nested arrays for more efficient execution after all subscriptions have been completed? I believe there may be a solution involving the use of pipes, mergeMaps, concatMaps, etc. this.teams = [ { Assignments: [{Id: ...

Is it recommended to use array_map and filter_var with $_POST in PHP?

Recently, I came across a clever piece of code for swiftly filtering $_POST data: $post=array_map("filter_data",$_POST); After updating it to the latest version (post PHP 5.2), here's what I ended up with: $post=array_map("filter_var",$_POST,array( ...

What is the best way to modify the inline style width of a table td from pixels to percentage in order to make it

<table> <tr style="height:15pt;"> <td style="width:229pt;border-style:solid;border-width:0pt;padding:3pt 9pt 3pt 0pt;" valign="bottom" bgcolor="#c0c0c0"><p style="font-family:Times New Roman, serif;font-size:10pt;font-style:norm ...

Dealing with blank values in jQuery DataTables

I am currently utilizing jQuery DataTable to display data in table format; within the table, there is a button that triggers a Bootstrap Modal for editing two of these values, and I utilize Ajax to send the modified values to a Spring Controller. The init ...

Sorting data in Javascript can be done efficiently by utilizing the .filter method

Can someone help me identify what I might be doing incorrectly? I have a chained filter under computed that is giving me an error message stating 'product.topic.sort' is not a function. My intention is to use 'select' to provide sortin ...

Struggling to access the html elements within a component once the ng2 page has finished loading?

I am working on a web app that utilizes ng2-smart-table and I want to hide all cells within the table. However, when attempting to retrieve all the cells using document.getElementsByTagName("td") in the ngAfterViewInit() lifecycle hook, I noticed that the ...

Chai spy does not recognize sinon stubbed functions when verifying function calls

I am working with two asynchronous functions that return bluebird promises: Async1: function() { return new Promise(function(resolve, reject) { execute(query) .then(function(resp) { resolve(resp); }) .catch(function(err) { ...

Invoke the function when you finish typing in React.js

After I finish typing, I want to execute some code. I attempted to use the following script but it didn't work as expected const stopTypingHandler=(e)=>{ let time; clearTimeout(time); time = setTimeout(() => { console.log("click& ...

Adjust the HTML Canvas to cover the entire screen

I am trying to adjust the HTML Canvas element so that its width matches the width of the browser window and its height matches the height of the browser window. Below is the code snippet I am using: HTML: <body> <canvas id="gameCanvas" ...

Unable to utilize query parameters with an ExpressJS API on localhost

Within my index.js file app.use('/api/v1/users', userRouter) In the Router file router.get("/:id", getUserDataById); When using Postman: The GET URL I am using is: http://localhost:3000/api/v1/users?id=120622 The error message is: C ...

Creating an organized array for control indexing?

Is there an index control arrays feature in C#? I am interested in creating a "button array" with 5 buttons that share a single event handler to manage all the controls based on their indexes, similar to how it is done in VB6. Otherwise, I would have to wr ...

What is the best way to add a div container to a particular section of a webpage?

I have come across many solutions that involve using JQuery, but I am specifically looking for a pure JS method. Currently, I create a div, add content to it using Create Element and innerHTML, and then use appendChild to place it at the bottom of the body ...