Skip to content
Advertisement

How to create multiple array of objects from single array of objects based on property value

If I have array of objects like this one I want to group it by property value

    const unitsPhotos = [{
    fieldname: 'unit_1',
    name: 'Photo 1',
    size: 324
  },
  {
    fieldname: 'unit_2',
    name: 'Photo 11',
    size: 321
  },
  {
    fieldname: 'unit_1',
    name: 'Photo 41',
    size: 541
  },
  {
    fieldname: 'unit_2',
    name: 'Photo 14',
    size: 123
  },
  {
    fieldname: 'unit_3',
    name: 'Photo 144',
    size: 1223
  }
  ];

How to create three new separate arrays of objects based on fieldname ( or single array that contains those arrays of objects ) something like this

const groupedArray = [
  [{
      fieldname: 'unit_1',
      name: 'Photo 1',
      size: 324
    },
    {
      fieldname: 'unit_1',
      name: 'Photo 132',
      size: 325
    }],
  [{
      fieldname: 'unit_2',
      name: 'Photo 11',
      size: 321
    },
    {
      fieldname: 'unit_2',
      name: 'Photo 14',
      size: 123
    }],
  [{
    fieldname: 'unit_3',
    name: 'Photo 144',
    size: 1223
  }]];

Advertisement

Answer

you can first unique the array and next push them to groupedArray like this:

 const unitsPhotos = [{
    fieldname: 'unit_1',
    name: 'Photo 1',
    size: 324
  },
  {
    fieldname: 'unit_2',
    name: 'Photo 11',
    size: 321
  },
  {
    fieldname: 'unit_1',
    name: 'Photo 41',
    size: 541
  },
  {
    fieldname: 'unit_2',
    name: 'Photo 14',
    size: 123
  },
  {
    fieldname: 'unit_3',
    name: 'Photo 144',
    size: 1223
  }
  ];
  
const unitsPhotosArr = unitsPhotos.map(item => item.fieldname)
// you can find uniques with this function
const toFindUniques = arry => arry.filter((item, index) => arry.indexOf(item) === index)
const uniques = toFindUniques(unitsPhotosArr);
const groupedArray = [];
for (const element of uniques) {
  const item = unitsPhotos.filter(el => el.fieldname === element);
  groupedArray.push(item)
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement