skip to Main Content

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


  1. 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});
      }
    });
    
    
    Login or Signup to reply.
  2. const input = [{
        "Person": "Bob",
        "Wants": "Shoes"
      },
      {
        "Person": "Bob",
        "Wants": "Socks"
      },
      {
        "Person": "Sam",
        "Wants": "Coffee"
      },
      {
        "Person": "Tim",
        "Wants": "Puppy"
      },
      {
        "Person": "Sam",
        "Wants": "Biscuit"
      }
    ];
    
    // a dictionary useful for later
    const people = {}
    
    // for each item of input
    for (const { Person, Wants } of input) {
      if (!(Person in people)) {
        // if the person is not yet in the dictionary add them
        people[Person] = { Person, Wants: [] }
      }
      // add another item to Wants array
      people[Person].Wants.push(Wants)
    }
    
    // convert dictionary to a list
    const result = Object.values(people)
    
    // replace Wants array with string
    for (const person of result) {
      person.Wants = person.Wants.join(', ')
    }
    
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search