Ok i have a array like the following
[
{data: Array(22), title: '1111'}
{data: Array(12), title: '2222'}
{data: Array(6), title: '1111'}
{data: Array(22), title: '3333'}
{data: Array(0), title: '4444'}
]
What i want to do this if there are objects with duplicate titles (like {data: Array(22), title: '1111'} and {data: Array(6), title: '1111'}), i want to merge the data arrays of the objects with equal titles.
So my final output should be like
[
{data: Array(28), title: '1111'}
{data: Array(12), title: '2222'}
{data: Array(22), title: '3333'}
{data: Array(0), title: '4444'}
]
I have tried some lodash functions as well and also javascript filter. I tried forEach ,mapping and etc. But cannot grasp the method to do what i need.
You can use Array#reduce.
let arr = [
{data: [1,2,3], title: '1111'},
{data: [4,5], title: '2222'},
{data: [6], title: '1111'},
{data: [7,8,9,10], title: '3333'},
{data: [11,12,13,14,15], title: '4444'}
]
let res = Object.values(arr.reduce((acc, {title, data})=>{
(acc[title] ??= {title, data: []}).data.push(...data);
return acc;
}, {}));
console.log(res);