1

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?

4
  • This is not valid json. You can have a comments array for each object? Commented Jun 28, 2022 at 19:58
  • I don't need it to be valid JSON I just need it to where I can run requests on each object. My api returns a new ID for the created Post, which I need access to so that I can create the Comments. When they are in separate objects, it makes that very difficult to do. Commented Jun 28, 2022 at 20:02
  • 1
    Is this a good format? [ { "Post": "post1", "Comments": [ "comment1", "comment2", "comment3" ] } ... ] Commented Jun 28, 2022 at 20:05
  • I can work with that ^ Commented Jun 28, 2022 at 20:06

1 Answer 1

1
  • Using 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 Post
  • Using Map#values, you can get a list of grouped objects

const 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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.