I have an array with many objects in it, all of them has the same keys and I want to merge them based on chapter name while not losing any of the other values
I tried different methods, which are lengthy and has not achieved the solution yet, hoping for a solution, which is optimized if possible
>Solution :
So basically for sort your problem of merge and group other data without loosing data of variables you need to try this code :
let array = [
{chapter: 'Case Studies', id: 1, proficiency: 'Basic', score: '0', count: '2'},
{chapter: 'Determinants', id: 1, proficiency: 'Basic', score: '0', count: '10'},
{chapter: 'Relations & Functions', id: 1, proficiency: 'Basic', score: '100.00', count: '13'},
{chapter: 'Case Studies', id: 2, proficiency: 'Intermediate', score: '0', count: '3'},
{chapter: 'Determinants', id: 2, proficiency: 'Intermediate', score: '10.53', count: '10'},
{chapter: 'Relations & Functions', id: 2, proficiency: 'Intermediate', score: '70.00', count: '10'},
{chapter: 'Case Studies', id: 3, proficiency: 'Advanced', score: '0', count: '1'},
{chapter: 'Relations & Functions', id: 3, proficiency: 'Advanced', score: '100.00', count: '6'}
];
let result = {};
array.forEach(function(item) {
if (result[item.chapter]) {
result[item.chapter].push({
id: item.id,
proficiency: item.proficiency,
score: item.score,
count: item.count
});
} else {
result[item.chapter] = [{
id: item.id,
proficiency: item.proficiency,
score: item.score,
count: item.count
}];
}
});
let finalResult = [];
for (let key in result) {
finalResult.push({
chapter: key,
values: result[key]
});
}
console.log(finalResult);
Result look like :

