Search code examples
javascriptlodash

Create a Map of Objects from an Array via Lodash


I have the following array of arrays consisting of a name, age, and department

[[ "Kevin", 22,"Psychology" ],
[ "Cathy", 26, "Psychology" ],
[ "David", 31, "Engineering" ],
[ "Christine", 23, "Engineering" ]]

I want to create a map based on the unique departments that would look like this:

{ Psychology: [ 
  { name: "Cathy", age: 26 }, 
  { name: "Kevin", age: 22 } ] 
},
{ Engineering: [ 
  { name: "Christine", age: 23 }, 
  { name: "David", age: 31 } ] 
}

The index of department in the array will always be same. How can this be done utilizing lodash?


Solution

  • Without using a external library, using new ESNext stuff like this is pretty easy.

    const data = [
    [ "Kevin", 22,"Psychology" ],
    [ "Cathy", 26, "Psychology" ],
    [ "David", 31, "Engineering" ],
    [ "Christine", 23, "Engineering" ]];
    
    const result = data.reduce((a, v) => {
      const [name,age,dept] = v; 
      (a[dept] = a[dept] || []).push({name,age});
      return a;
    }, {});
    
    console.log(result);