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
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.
const key = Object.keys(current)[0])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)
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)
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.