Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Avoid sorting in groupBy lodash method

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' } ],
    }
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!