This question has already been answered:

There is an array of the form:

var data = [ {"time":["00:00"],"workstation":4,"worker":4}, {"time":["00:00","01:45","03:30","05:15","07:00","08:45","10:30","12:15","14:00"],"workstation":11,"worker":4}, {"time":["02:40"],"workstation":14,"worker":1}, {"time":["02:40"],"workstation":4,"worker":1}, {"time":["17:30","19:15","21:00","22:45"],"workstation":4,"worker":1}, {"time":["17:30","19:15","21:00","22:45"],"workstation":14,"worker":1} ]; 

(The time is stored in the timestamp. For the sake of simplicity, I have done so far in a normal format. Here the source array is http://jsfiddle.net/p2exsn36/1/ )

That is, each element is an object of the form:

  { "time" : [], "workstation" : 14, "worker" : 1 } 

There are duplicates of time in this object in the time array, a worker can also be different and workstation. At the exit, I would like to get a "clean" array of the form:

 [ {"time" : "00:00", "workstation" : [14,5], "worker" : [1,4]}, {"time" : "01:45", "workstation" : [11], "worker" : [4]} ] 

Tell me, please, how can they be glued correctly? Thank! Just starting to learn javascript

Reported as a duplicate by participants of Rolandius , Aries , aleksandr barakin , Mstislav Pavlov , xaja 6 Oct '15 at 11:56 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • And what moment causes difficulties? Have you ever tried to do something yourself? - Petr Abdulin
  • four
    If I honestly don’t see any significant differences with these questions of yours: one , two - Rolandius

1 answer 1

Something like this, just need to rewrite on ES5:

 var data = [ {"time":["00:00"],"workstation":4,"worker":4}, {"time":["00:00","01:45","03:30","05:15","07:00","08:45","10:30","12:15","14:00"],"workstation":11,"worker":4}, {"time":["02:40"],"workstation":14,"worker":1}, {"time":["02:40"],"workstation":4,"worker":1}, {"time":["17:30","19:15","21:00","22:45"],"workstation":4,"worker":1}, {"time":["17:30","19:15","21:00","22:45"],"workstation":14,"worker":1} ]; var res = Object.create(null), item, time, cur; for (item of data) { for (time of item.time) { cur = res[time] = res[time] || { time:time, workstation:[], worker:[] }; ~cur.workstation.indexOf(item.workstation) || cur.workstation.push(item.workstation); ~cur.worker.indexOf(item.worker) || cur.worker.push(item.worker); } } res = Object.keys(res).map(function(key) { return res[key] }); console.log(JSON.stringify(res, null, " ")); 

  • jsfiddle.net/marcuzy/p2exsn36/2 is like that. thanks - ennet
  • @ennet, do not go through arrays with for-in - this is inefficient and potentially dangerous. Use a normal loop to the length of the array. Further, why the key itself assign the key as a value, I do not understand. And finally, what you get there does not correspond to what you asked in the question. - Qwertiy