Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

group array and join strings Javascript

I have an array that looks something like this:

let result = [{"Person": "Bob","Wants":"Shoes"},
 {"Person": "Bob","Wants":"Socks"},
 {"Person": "Sam","Wants":"Coffee"},
 {"Person": "Tim","Wants":"Puppy"},
 {"Person": "Sam","Wants":"Biscuit"}];

I would like to convert it into an array that looks like this:

let summary  = [{"Person":"Bob","Wants":"Shoes, Socks"},
 {"Person":"Sam","Wants":"Coffee, Biscuit"},
 {"Person":"Tim","Wants":"Puppy"}];

I am very new to Javascript; it seems maybe I want to map or reduce the result array, but each time I try I get completely tied up in callbacks and foreach loops. Is there a simple way to join the strings in the second (Wants) column, when grouped by the first column?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use forEach (or map) to see if the person in ‘result’ exists in ‘summary’ (assuming summary is an empty array to begin with), and if it does, add to that person’s ‘wants’.

let result = [
  {"Person": "Bob", "Wants": "Shoes"},
  {"Person": "Bob", "Wants": "Socks"},
  {"Person": "Sam", "Wants": "Coffee"},
  {"Person": "Tim", "Wants": "Puppy"},
  {"Person": "Sam", "Wants": "Biscuit"}
];

let summary = [];

result.forEach(item => {
  let existingPerson = summary.find(summaryItem => summaryItem.Person === item.Person);

  if (existingPerson) {
    existingPerson.Wants += `, ${item.Wants}`;
  } else {
    summary.push({"Person": item.Person, "Wants": item.Wants});
  }
});

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading