Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

364
Visualizações
How to find the frequency of a value, in a list of dictionaries?

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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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`)

about 4 years ago · Juan Pablo Isaza Relatório

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda