2

I'm working on an array which needs to be grouped, but original order to be maintained. So I tried alternate solutions but still that is not maintaining original array order. Resulting Order should be according to the 'year' in original array. Below is the array and its solution with result and expected object

  const cars = [
      {
          'make': 'ford',
          'model': 'fusion',
          'year': '2015'
      },
      {
          'make': 'audi',
          'model': 'r8',
          'year': '2012'
      },
{
          'make': 'ford',
          'model': 'fusion',
          'year': '2015'
      },    
{
      'make': 'honda',
      'model': 'city',
      'year': '2012'
  },
       {
          'make': 'audi',
          'model': 'rs5',
          'year': '2013'
      },
      {
          'make': 'ford',
          'model': 'mustang',
          'year': '2012'
      },
    ];

function groupBy(data, property) {
  return data.reduce((acc, obj) => {
    const key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}
const reGroup = (list, key) => {
    const newGroup = {};
    list.forEach(item => {
        const newItem = Object.assign({}, item);
        newGroup[item[key]] = newGroup[item[key]] || [];
        newGroup[item[key]].push(newItem);
    });
    return newGroup;
};

console.log(reGroup(cars, 'year'));
console.log(groupBy(cars, 'year'));

output -
 {
  '2012': [
    { make: 'audi', model: 'r8', year: '2012' },
    { make: 'honda', model: 'city', year: '2012' },
    { make: 'ford', model: 'mustang', year: '2012' }
  ],
  '2013': [ { make: 'audi', model: 'rs5', year: '2013' } ],
  '2015': [
    { make: 'ford', model: 'fusion', year: '2015' },
    { make: 'honda', model: 'city', year: '2015' }
  ]
}

expected- 
   {
     '2015': [
        { make: 'ford', model: 'fusion', year: '2015' },
        { make: 'honda', model: 'city', year: '2015' }
      ]
      '2012': [
        { make: 'audi', model: 'r8', year: '2012' },
        { make: 'honda', model: 'city', year: '2012' },
        { make: 'ford', model: 'mustang', year: '2012' }
      ],
      '2013': [ { make: 'audi', model: 'rs5', year: '2013' } ],
    }
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Abhishek Konnur
  • 503
  • 1
  • 9
  • 33

0 Answers0