I have an array of arrays of objects which looks like this:
let fruitSamples = [
[
{'id': 1,'type': 'apples','samples': [1, 2, 3]},
{'id': 2,'type': 'bananas','samples': [1, 2, 7]},
{'id': 3,'type': 'pears','samples': [1, 2, 3]}
],
[
{'id': 1,'type': 'apples','samples': [5, 2, 9]},
{'id': 2,'type': 'bananas','samples': [1, 7, 7]},
{'id': 3,'type': 'pears','samples': [12, 21, 32]}
],
[
{'id': 1,'type': 'apples','samples': [11, 2, 33]},
{'id': 2,'type': 'bananas','samples': [17, 2, 67]},
{'id': 3,'type': 'pears','samples': [91, 22, 34]}
]
];
I want to reduce and merge the above array using lodash into one so that the samples get concatenated together like so:
fruitSamples = [
{'id': 1, 'type': 'apples', 'samples': [1,2,3,5,2,9,11,2,33]},
{'id': 2, 'type': 'bananas', 'samples': [1,2,7,1,7,7,17,2,67]},
{'id': 3, 'type': 'pears', 'samples': [1,2,3,12,21,32,91,22,34]},
]
I have tried many different approaches but since I want the shortest possible way of solving this what would be your recommendations?
I have tried this:
let test = _(fruitSamples)
.flatten()
.groupBy('type')
.map(_.spread(_.merge))
.value();
console.log(test);
This gives me the following result, which does not concatenate the samples:
test = [
{'id': 1,'type': 'apples','samples': [11, 2, 33]},
{'id': 2,'type': 'bananas','samples': [17, 2, 67]},
{'id': 3,'type': 'pears','samples': [91, 22, 34]}
]
I feel using _.mergeWith might be the right answer, if so, I am looking for help implementing mergeWith in the best possible way as I am not sure how to do it. Any suggestions?