Home > Software engineering >  How to find the frequency of a value, in a list of dictionaries?
How to find the frequency of a value, in a list of dictionaries?

Time:07-04

Say we have the following array of dictionaries:

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}
                         ]
                      ]

How would I get the output that tells me:

in georgia: sunny occurs 2 times, and rainy occurs 1 time.

In france: rainy occurs 1 time, gloomy occurs 1 time, and dry occurs 1 time

CodePudding user response:

With an array of arrays (proper terminology for a dictionary in JS is array), it would be easy to use the flatMap to get extract all values from the inner arrays into the outer array. From there you can iterate over the flattened array and collect the values you want.

For this example, I might use the array.reduce method to transform the resulting flat array into an object with a key for each country, and the value being another object with keys for each weather type, and value of the 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 array
  const flatArr = arr.flatMap(a => a)

  // use flattened array to transform the values into frequencies
  const sortedArr = flatArr.reduce((accum, { country, value }) => {

    // check if key exists, if not, add it
    if (!accum[country]) accum[country] = {}

    // check if weather type exists, if so add 1, if not, assign 1
    accum[country][value] ? accum[country][value]  = 1 : accum[country][value] = 1

    // return the accumulator for the next iteraction of `reduce`
    return accum
  }, {})
  return sortedArr
}

// check resulting object from the `reduce` function
console.log(weatherFrequency(dictionary_demo))

// produce a string with the values you want
const countryWeather = weatherFrequency(dictionary_demo)

// use string interpolation to extract values you need
console.log(`in georgia: sunny occurs ${countryWeather.georgia.sunny} times, and rainy occurs ${countryWeather.georgia.rainy} time`)

CodePudding user response:

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"}
   ]
]

var res = dictionary_demo.reduce(function(acc,e){
    
    return acc.concat(e);

},[]).reduce(function(acc, e){

    if(!acc[e.country])
        acc[e.country] = {[e.value]: 1};
    else
        acc[e.country][e.value] = (acc[e.country][e.value] ||  0)   1;

    return acc;
    
}, {});

console.log(res)

CodePudding user response:

Since this is an array of array, you can flat that arrays with depth = 2, and then you can use the function Array.prototype.reduce to build 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; }

  • Related