0

I have array structure of employee information in JavaScript

var emplyeeinfo=[{
    empNo: 12302,
    empId: '30984',
    empJobCategory: 'Designer',
  },
  {
    empNo: 14785,
    empId: '33420',
    empJobCategory: 'Associate Manager',
  },
  {
    empNo: 13710,
    empId: '32603',
    empJobCategory: 'Designer',
  },
  {
    empNo: 13783,
    empId: '32675',
    empJobCategory: 'Designer',
  },
  {
    empNo: 15069,
    empId: '33619',
    empJobCategory: 'Designer',
  },
  {
    empNo: 14285,
    empId: '33020',
    empJobCategory: 'Validator',
  },
  {
    empNo: 14476,
    empId: '33185',
    empJobCategory: 'Designer',
  }];

and want to build array from above information

var employeejob=[{'Designer':[12302,13710,13783,15069,14476]},
                    {'Associate Manager':[14785]},
                    {'Validator':'[14285]}
                    ];

I did not find any proper mechanism to build this array in JavaScript and from this array want to build following array for high-chart series

    var finalchart={series:[7,5,1,1], 
category:['Total','Designer','Associate Manager','Validator']}; 
3
  • Seems like some backend guy don't want to send the exact data. Commented Apr 12, 2016 at 7:15
  • i provided exact data Commented Apr 12, 2016 at 7:17
  • @anagha affinity you can build object of employeejob and than loop through your main loop and add specefic property you need in employeejob Commented Apr 12, 2016 at 7:20

2 Answers 2

3

Try this:

// Your new object
var obj = {};
// loop through the objects in array
employeeinfo.map(function(e){
   // check if the object is already created or not
   if(!obj[e.empJobCategory]){
       // if not created then initialize it as an array
       obj[e.empJobCategory] = [];
   }
   // push the new empNo in the created/present array
   obj[e.empJobCategory].push(e.empNo);
});

// see the output
console.dir(obj);

Working Fiddle

Can also be done using Array.reduce().

var obj = employeeinfo.reduce(function(p, c, i, a) {
  if (!p[c.empJobCategory]) {
    p[c.empJobCategory] = [];
  }
  p[c.empJobCategory].push(c.empNo);
  return p;
}, {});

console.dir(obj);

Working Fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

You can try another way

function groupBy( array , f )
{
  var groups = {};
  array.forEach( function( o )
  {
    var group = JSON.stringify( f(o) );
    groups[group] = groups[group] || [];
    groups[group].push( o.empNo );  
  });
  return Object.keys(groups).map( function( group )
  {
    return groups[group]; 
  })
}

Then

var result = groupBy(employeeinfo, function(item)
{
  return [item.empJobCategory];
});

The print

console.dir(result)

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.