Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
Grouping a javascript array over a loop

I have the following array:

[
    {'id': 1, 'rating': 5, 'rating_category': "a"},
    {'id': 1, 'rating': 1, 'rating_category': "a"},
    {'id': 1, 'rating': 4, 'rating_category': "b"},
    {'id': 1, 'rating': 5, 'rating_category': "b"},
]

And expect the following array:

[
   { category: "a", rating_average: 3, rating_count: 2},
   { category: "b", rating_average: 4.5, rating_count: 2},
]

My approach works only partially. I just don't get the array format I want. I get a [key : {}, key : {}] but I want to get [{},{}]. My problem is checking if the key already exists in the array.

const data = [
    {'id': 1, 'rating': 5, 'rating_category': "a"},
    {'id': 1, 'rating': 1, 'rating_category': "a"},
    {'id': 1, 'rating': 4, 'rating_category': "b"},
    {'id': 1, 'rating': 5, 'rating_category': "b"},
]

r = []
data.forEach(e => {
  if (! r[e.rating_category]) {
    r[e.rating_category] = {
      rating: e.rating, 
      count: 1      
    };
  } else {    
    r[e.rating_category]['rating'] += e.rating
    r[e.rating_category]['count']++
  }
  
})
console.log(r.a, r.b)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Add the category as a property in the object. Then at the end you can use Object.values() to get all the properties as an array.

r should be an object, not an array.

const data = [
    {'id': 1, 'rating': 5, 'rating_category': "a"},
    {'id': 1, 'rating': 1, 'rating_category': "a"},
    {'id': 1, 'rating': 4, 'rating_category': "b"},
    {'id': 1, 'rating': 5, 'rating_category': "b"},
]

const r = {};
data.forEach(e => {
  if (! r[e.rating_category]) {
    r[e.rating_category] = {
      category: e.rating_category,
      rating: e.rating, 
      count: 1      
    };
  } else {    
    r[e.rating_category]['rating'] += e.rating
    r[e.rating_category]['count']++
  }
  
})
console.log(Object.values(r))

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here's a way you can do it fairly efficiently. Basically the idea is to group the ratings by category first, then calculate the length and average of the ratings for each category and then format your return value, like so:

let data = [
    {'id': 1, 'rating': 5, 'rating_category': "a"},
    {'id': 1, 'rating': 1, 'rating_category': "a"},
    {'id': 1, 'rating': 4, 'rating_category': "b"},
    {'id': 1, 'rating': 5, 'rating_category': "b"},
]
// group the ratings by category
let grouped = data.reduce((res, curr) => {
  if (!res[curr.rating_category]) {
    res[curr.rating_category] = [];
  }
  res[curr.rating_category].push(curr.rating);
  return res;
}, {});
// calculate length & average of each category and format return value
let formatted = Object.entries(grouped).map(([key, value]) => {
  let average = value.reduce((res, curr) => res + curr, 0) / value.length;
  return { category: key, rating_count: value.length, rating_average: average }
});

console.log(formatted)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could take a function for grouping, like the (hopefully) upcoming new prototype Array#groupBy and take the average by using a sum function and return a new object for each group.

Array.prototype.groupBy ??= function (callbackfn, thisArg) {
    const O = Object(this);
    const len = O.length >>> 0;
    if (typeof callbackfn !== 'function') throw new TypeError(callbackfn + ' is not a function');

    let k = 0;
    const groups = {};

    while (k < len) {
        const Pk = Number(k).toString();
        const kValue = O[Pk];
        const propertyKey = callbackfn.call(thisArg, kValue, Number(k), O);
        (groups[propertyKey] ??= []).push(kValue);
        ++k;
    }
    return groups;
};

const
    sum = (array, key) => array.reduce((s, v) => s + (key ? v[key] : v), 0),
    data = [{ id: 1, rating: 5, rating_category: "a" }, { id: 1, rating: 1, rating_category: "a" }, { id: 1, rating: 4, rating_category: "b" }, { id: 1, rating: 5, rating_category: "b" }],
    result = Object
        .entries(data.groupBy(({ rating_category }) => rating_category))
        .map(([category, a]) => ({ category, rating_average: sum(a, 'rating') / a.length, rating_count: a.length }));

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda