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?
2
Answers
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’.