Search code examples
javascriptarrayssortingjavascript-objects

How can I regroup Array of objects by given field


I have given array of objects, something like this

const data = [
    {id: 1,  name: 'Alex', job: 'IT'},
    {id: 2,  name: 'Pavel', job: 'IT'},
    {id: 3,  name: 'Joe', job: 'IT'},
    {id: 4,  name: 'Josh', job: 'IT'},
    {id: 5, name: 'Max', job: 'teacher'},
    {id: 6, name: 'Sam', job: 'teacher'}
]

I need array of arrays filtered by field job

const result = [
    {job: 'IT', 
    workersInfo: [
    {id:1, name:'Alex'}, 
    {id:2, name:'Pavel'}, 
    {id:3, name:'Joe'}, 
    {id:4, name:'Josh'}
    ]
    }, 
    {job: 'teacher', 
    workersInfo: [
    {id:5, name: 'Max'}, 
    {id:6, name: 'Sam'}
    ]  
    }
]

I tried this, but It's not what I want

const data = [
    {id: 1,  name: 'Alex', job: 'IT'},
    {id: 2,  name: 'Pavel', job: 'IT'},
    {id: 3,  name: 'Joe', job: 'IT'},
    {id: 4,  name: 'Josh', job: 'IT'},
    {id: 5, name: 'Max', job: 'teacher'},
    {id: 6, name: 'Sam', job: 'teacher'}
]

const groupList = data.reduce((reduce, it) => { 
        reduce[it.job] = reduce[it.job] || [];
        reduce[it.job].push({id: it.id, name: it.name});
        return reduce;
 }, {})


console.log(Object.values(groupList));

How can I add new key workers Info and push info to this field


Solution

  • If you create a new object on each iteration instead of an array you can then use Object.values:

    const data = [
      {id: 1,  name: 'Alex', job: 'IT'},
      {id: 2,  name: 'Pavel', job: 'IT'},
      {id: 3,  name: 'Joe', job: 'IT'},
      {id: 4,  name: 'Josh', job: 'IT'},
      {id: 5, name: 'Max', job: 'teacher'},
      {id: 6, name: 'Sam', job: 'teacher'}
    ];
    
    const groupList = data.reduce((acc, { job, id, name }) => {
      acc[job] = acc[job] || { job, workersInfo: [] };
      acc[job].workersInfo.push({ id, name });
      return acc;
    }, {})
    
    
    console.log(Object.values(groupList));