0

I need to split an Array by its objects subvalue (type). Let's assume I have following array:

[
  {id:1,name:"John",information: { type :"employee"}},
  {id:2,name:"Charles",information: { type :"employee"}},
  {id:3,name:"Emma",information: { type :"ceo"}},
  {id:4,name:"Jane",information: { type :"customer"}}
]

and I want to split the object by information.type so my final result looks like:

[
 {
  type:"employee",
  persons:
  [
   {id:1,name:"John",information: { ... }},
   {id:2,name:"Charles",information: { ... }
  ]
 },
{
  type:"ceo",
  persons:
  [
   {id:3,name:"Emma",information: { ... }}
  ]
 },
{
  type:"customer",
  persons:
  [
   {id:4,name:"Jane",information: { ... }}
  ]
 }, 
]

Underscore is available at my Project. Any other helper library could be included.

Of course I could loop through the array and implement my own logic, but i was looking for cleaner solution.

1
  • please add your solution. Commented Apr 12, 2016 at 16:09

3 Answers 3

3

This returns exactly what you want:

_.pairs(_.groupBy(originalArray, v => v.information.type)).map(p => ({type: p[0], persons: p[1]}))
Sign up to request clarification or add additional context in comments.

Comments

1

A solution in plain Javascript with a temporary object for the groups.

var array = [{ id: 1, name: "John", information: { type: "employee" } }, { id: 2, name: "Charles", information: { type: "employee" } }, { id: 3, name: "Emma", information: { type: "ceo" } }, { id: 4, name: "Jane", information: { type: "customer" } }],
    result = [];

array.forEach(function (a) {
    var type = a.information.type;
    if (!this[type]) {
        this[type] = { type: type, persons: [] };
        result.push(this[type]);
    }
    this[type].persons.push({ id: a.id, name: a.name });
}, {});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Comments

0

You could use the groupBy function of underscore.js:

var empList = [
{id:1,name:"John",information: { type :"employee"}},
  {id:2,name:"Charles",information: { type :"employee"}},
  {id:3,name:"Emma",information: { type :"ceo"}},
  {id:4,name:"Jane",information: { type :"customer"}}
];
_.groupBy(empList, function(emp){ return emp.information.type; });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.