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

137
Visualizações
compute average of the first item in two dimensional array

I have this two dimensional array

var data = [
['12-9', 134],
['12-9', 148],
['12-9', 92],
['1-8', 116],
['1-8', 136],
['1-8', 150],
['21-5', 138],
['21-5', 143],
['21-5', 119],
['21-5', 125]
]

and I if the first value of an item matches the one of the others I want to compute the averrage of the second one.

e.g.: th e first 3 elements all have "12-9" and for that it should give me 124,7 because (137+148+92) / 3 = 124,7.

This might be very easy but I'm stuck. I tried it with map() and reduce() or filter() but nothing works for me. I'm very shure that I not to see the obvious things here.

And now I dumped everything down again and this is my new starting point now:

  for (let item of data) {
    var temp = item[0];
    var myValues = data.filter((value) => {
      return value[0] === temp;
    });
    console.log(myValues );
  }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Filter and reduce is what you need

const data = [['12-9', 134],['12-9', 148],['12-9', 92],['1-8', 116],['1-8', 136],['1-8', 150],['21-5', 138],['21-5', 143],['21-5', 119],['21-5', 125]];

const avg = data.reduce((acc, item) => {
  const key = item[0]
  if (!acc[key]) {
    const same = data
      .filter(nums => nums[0] === key);

    acc[key] = {
      count: same.length,
      avg: +(same.reduce((acc, [key, num]) => acc + num, 0) / same.length).toFixed(2) // key is ignored we could use an underscore to show that
    }
  }
  return acc
}, {})
console.log(avg)

about 4 years ago · Juan Pablo Isaza Relatório

0

Here's an example reducing into a Map grouped by the first element, and then iterating over the result to average the grouped arrays and rebuild the shape of the original array.

const data = [['12-9', 134], ['12-9', 148], ['12-9', 92], ['1-8', 116], ['1-8', 136], ['1-8', 150], ['21-5', 138], ['21-5', 143], ['21-5', 119], ['21-5', 125],];

const map = data.reduce((a, [k, v]) => a.set(k, [...(a.get(k) ?? []), v]), new Map());

const result = [...map.entries()].map(([k, vs]) => [k, vs.reduce((a, b) => a + b) / vs.length]);

console.log(result);

Or similar logic applied in successive for...of loops, but this time tracking a running sum and count of each element thus avoiding the later reduce to calculate the average.

const data = [['12-9', 134], ['12-9', 148], ['12-9', 92], ['1-8', 116], ['1-8', 136], ['1-8', 150], ['21-5', 138], ['21-5', 143], ['21-5', 119], ['21-5', 125],];

const map = new Map();
for (const [key, value] of data) {
  if (!map.has(key)) {
    map.set(key, { sum: 0, count: 0 });
  }

  map.get(key).count += 1;
  map.get(key).sum += value;
}

const result = [];
for (const [key, { sum, count }] of map) {
  result.push([key, sum / count]);
}

console.log(result);

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