1

The data received from the api is not in the format I wanted so having to re-map it. I have an array of people and I want to group them to the team they belong to. I have to first iterate through each person and get the team name. Do a distinct on team name, create a new array of object and then assign them to the correct team.

    [{name: 'John', age: 23,  teamName: 'Development' },
    {name: 'Ben', age: 50, teamName: 'Development' },
    {name: 'Matt', age: 24, teamName: 'Finance' },
    {name: 'Amy', age: 35, teamName: 'Sales' },
    {name: 'Laura', age: 31, teamName: 'Finance' }]

This is what I have attempted to get the distinct teams...

const staffs = res._embedded['staff'];

const teams = staffs.map(staff => staff.teamName);

const distinctTeams = [...new Set(teams)];

Map them to correct teams

const teamsWithStaff = staffs.map(staff =>
                        distinctTeams[staff.teamName].push({ name: staff.name, age: staff.age })
                    );
coding1223322
  • 461
  • 11
  • 26

1 Answers1

0

You can use reduce and group values based on teamName

let data =[{name: 'John', age: 23,  teamName: 'Development' },{name: 'Ben', age: 50, teamName: 'Development' },{name: 'Matt', age: 24, teamName: 'Finance' },{name: 'Amy', age: 35, teamName: 'Sales' },{name: 'Laura', age: 31, teamName: 'Finance' }]
    
let op = data.reduce((op,inp) => {
  let {teamName} = inp
  op[teamName] = op[teamName] || []
  op[teamName].push(inp)
  return op
},{})

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60