Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
replace duplicates in an array with new values from object

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!