I have an array like this:
var arr = [
{
revision: 19,
text: 'hello',
details: [
{
id: 5
}
]
},
{
revision: 19,
text: 'hello',
details: [
{
id: 6
}
]
},
{
revision: 17,
text: 'world',
details: [
{
id: 7
}
]
}
];
And I'd like to concat its details arrays if the revision is the same (the text values are the same if they got the same revision value):
var expected = [
{
revision: 19,
text: 'hello',
details: [
{
id: 5
},
{
id: 6
}
]
},
{
revision: 17,
text: 'world',
details: [
{
id: 7
}
]
}
];
Here is what I came up with:
constructArray(groupByRevisionNb(arr));
function groupByRevisionNb(arr) {
return _.groupBy(arr, 'revision');
}
function constructArray(obj) {
return _.map(obj, function (arr) {
return concatRevisions(arr);
});
}
function concatRevisions(arr) {
return _.reduce(arr, function (obj1, obj2) {
if (_.isEmpty(obj1)) {
obj1 = _.clone(obj2);
} else {
obj1.details = obj1.details.concat(obj2.details);
}
return obj1;
}, {});
}
But I'm not 100% satisfied with it. What could be improved?
I'm not using ES6.
textwhen merging? \$\endgroup\$textvalues are the same if they got the samerevisionvalue \$\endgroup\$