Search code examples
javascriptecmascript-6lodash

Use Lodash map to reorganize list into sorted keys by value


I am can't figure out how to do this without iterating over the array three times.

I am looking to transform an array of job listings that look like this:

const jobs = [
  {
    title: 'Manager',
    department: 'Retail',
    location: 'New York'
  },
  {
    title: 'Customer Service Rep',
    department: 'Corporate',
    location: 'Washington D.C.'
  },
  {
    title: 'Clerk',
    department: 'Retail',
    location: 'New York'
  },
  ...
];

Into an object of unique departments with associated jobs:

const deps = {
  'Corporate': [
    {
      title: 'Customer Service Rep',
      department: 'Corporate',
      location: 'Washington D.C.'
    },
  ],
  'Retail': [
    {
      title: 'Manager',
      department: 'Retail',
      location: 'New York'
    },
    {
      title: 'Clerk',
      department: 'Retail',
      location: 'New York'
    },
  ],
};

Is _map my best bet here? Is there a more eloquent way of doing this?


Solution

  • You can use array#reduce to group jobs based on department.

    const jobs = [ { title: 'Manager', department: 'Retail', location: 'New York' }, { title: 'Customer Service Rep', department: 'Corporate', location: 'Washington D.C.' }, { title: 'Clerk', department: 'Retail', location: 'New York' }],
        deps = jobs.reduce((r,job) => {
          r[job.department] = r[job.department] || [];
          r[job.department].push(job);
          return r;
        },{});
    console.log(deps);

    You can use _.groupBy

    const jobs = [ { title: 'Manager', department: 'Retail', location: 'New York' }, { title: 'Customer Service Rep', department: 'Corporate', location: 'Washington D.C.' }, { title: 'Clerk', department: 'Retail', location: 'New York' }],
        deps = _.groupBy(jobs, 'department');
    console.log(deps);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>