I'm trying to "flatten" an array that has multiple duplicate values. The array is created from a CSV that I'm then trying to run API requests on. The format of the CSV is as follows:
Posts | Comments |
post1 comment1
post1 comment2
post1 comment3
post2 comment1
post2 comment2
post2 comment3
I'm using Papaparse which returns:
[{Post: 'post1', Comment: 'comment1'}, {Post: 'post1', Comment: 'comment2'}, ...]
So I thought I would try to flatten them to where it would look like:
[{Post: 'post1', {Comment: 'comment1'}, {Comment: 'comment2'}}]
I tried using a .map and referencing the index to check if the previous Post was the same as the current Post if it is then .push to the previous index which I can't do using .map
What would be the correct way of doing this?
Array#reduce, iterate over the list while updating a Map where the Post is the key and the value is an object with Post and grouped Comments array for the PostMap#values, you can get a list of grouped objectsconst data = [ { Post: 'post1', Comment: 'comment1' }, { Post: 'post1', Comment: 'comment2' }, { Post: 'post1', Comment: 'comment3' }, { Post: 'post2', Comment: 'comment1' }, { Post: 'post2', Comment: 'comment2' }, { Post: 'post2', Comment: 'comment3' } ];
const res = [...
data.reduce((map, { Post, Comment }) => {
const { Comments = [] } = map.get(Post) ?? {};
map.set(Post, { Post, Comments: [...Comments, Comment] });
return map;
}, new Map)
.values()
];
console.log(res);