-1

I have an array of objects (Employee {role: string, members: string []})

array = [{
  role: 'doctor',
  fullName: 'x'
}, {
  role: 'nurse',
  fullName: 'y'
}, {
  role: 'doctor',
  fullName: 'z'
}]

and I want to group objects by role in a new array (result) in typescript

result = [{
    role: 'doctor',
    members: ['x', 'z']
  } {
    role: 'nurse',
    members: ['y']
  }
}

My code:

result = array.map(function(pemp: any) {

  if (!array.some(function(el: any) {
    return el.role === pemp.role;
  })) {
    return new Employee(pemp.role, pemp.fullName);
  } else {
    var pos = this.result.map(function(e: any) {
      return e.role;
    }).indexOf(pemp.role);
    this.result[pos].members.push(pemp.fullName)
  }
});
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Karen
  • 3
  • 4
  • Possible duplicate of [What is the most efficient method to groupby on a javascript array of objects?](http://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – Andreas Jun 08 '16 at 11:09
  • I think it's not typescript issue. It's about your coding javascript skill. – Tony Jun 08 '16 at 16:04

2 Answers2

0

You can try something like this:

var data = [{
  role: 'doctor',
  fullName: 'x'
}, {
  role: 'nurse',
  fullName: 'y'
}, {
  role: 'doctor',
  fullName: 'z'
}];

var obj = {};
data.forEach(function(item){
  if(!obj[item.role]) obj[item.role] = [];
  obj[item.role].push(item.fullName);
});

var result = Object.keys(obj).map(function(k){
  return {role:k, members: obj[k]}
});

document.getElementById("result").innerHTML = JSON.stringify(result,0,4)
<pre id="result"></pre>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

While this is not a solution in typescript, you could use a single loop with Array#forEach and a temporary object as reference to the result array for grouped roles.

var array = [{ role: 'doctor', fullName: 'x' }, { role: 'nurse', fullName: 'y' }, { role: 'doctor', fullName: 'z' }],
    result = [];

array.forEach(function (a) {
    if (!this[a.role]) {
        this[a.role] = { role: a.role, members: [] };
        result.push(this[a.role]);
    }
    this[a.role].members.push(a.fullName);
}, Object.create(null));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392