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

160
Vistas
Transform javascript array of objects

Could you please suggest any shorter code to solve following problem. I have array of objects:

const arr1=[
  { '1': { grade: 1.3, counter: 2 } },
  { '1': { grade: 2.8, counter: 2 } },
  { '2': { grade: 4.5, counter: 1 } },
  { '2': { grade: 2.4, counter: 1 } }
]

the output should look like:

const obj1={ 
             '1': {grade:4.1,counter:4}
             '2': {grade:6.9,counter:2}
}

here is the code i have tried :

arr1.reduce((acc,e)=> {
  let element = Object.keys(e)
  if(!acc.hasOwnProperty(element)){
    acc[element]={grade:0,counter:0}

  }
  acc[element].grade+= e[element].grade
  acc[element].counter+= e[element].counter
  return acc
}, {})

Thank you

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

0

Your problem here is that Object.keys(e) return an array of keys and not a single key.

If your object will always be the same (with one key) the you can get the key with : let element = Object.keys(e)[0]

I've decomposed the code with 2 main parts.

  • Getting the key of the current item (with const key = Object.keys(current)[0])
  • Checking if the newObject has the key
  • If yes : updating the grade and counter value with the current object
  • If no : adding the current object to the key

const arr1 = [{
    '1': {
      grade: 1.3,
      counter: 2
    }
  },
  {
    '1': {
      grade: 2.8,
      counter: 2
    }
  },
  {
    '2': {
      grade: 4.5,
      counter: 1
    }
  },
  {
    '2': {
      grade: 2.4,
      counter: 1
    }
  }
]

const newObject = arr1.reduce((newObject, current) => {
  const key = Object.keys(current)[0]
  const associatedObject = newObject[key]
  if (associatedObject) {
    associatedObject.grade += current[key].grade
    associatedObject.counter += current[key].counter
  } else {
    newObject[key] = current[key]
  }
  
  return newObject
}, {})

console.log(newObject)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this

let arr1=[{'1': {grade: 1.3, counter: 2}},{'1': {grade: 2.8, counter: 2}},{'2': {grade: 4.5, counter: 1}},{'2': {grade: 2.4, counter: 1}}];

arr1 = arr1.reduce((acc, obj) => {
    let [k, v] = Object.entries(obj)[0];
    if(!acc.hasOwnProperty(k)) acc[k] = {grade:0,counter:0};
    acc[k].grade += v.grade;
    acc[k].counter += v.counter;
    return acc
}, {});

console.log(arr1)

about 4 years ago · Juan Pablo Isaza Denunciar

0

I would go for:

arr1.reduce((o,n)=>{
  Object.keys(n).forEach((key)=>{
    if(!o[key]) o[key]={grade:0, counter:0};
    o[key]["grade"] += n[key]["grade"];
    o[key]["counter"] += n[key]["counter"]; 
  });
 return o;
},{});

Step1: reducing over the array, acc = {}

Step2: iterating over every key of the object at the current index

Step3: summing up the according properties

You forgot to iterate over the keys.

Comment: As a pons asinorum I use for array.reduce() the variable names:

  • o meaning old value (=acc=_accumulator)
  • n meaning new value.
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