JAVASCRIPT ARRAY (map and reduce)

Asked

Viewed 81 times

0

How are you guys

I have here this array:

[
  {dia:2,turno: turno1,M:1,T:0,N:0},
  {dia:2,turno: turno2,M:0,T:2,N:0},
  {dia:2,turno: turno3,M:0,T:0,N:1},
    
  {dia:3,turno: turno1,M:122,T:0,N:0},
  {dia:3,turno: turno2,M:0,T:21,N:0},
  {dia:3,turno: turno3,M:0,T:0,N:12}
]

i want to turn it to that array here!!

[
    {dia:2,turno1:1,turno2:2,turno3:1},
    {dia:3,turno1:122,turno2:21,turno3:12},
]

having regard to the fact that: In the

day 2 on shift 1 it sums up all values of M

day 2 on shift 2 it sums up all values of T

day 2 on shift 3 it sums up all values of N

Same thing happens on the 3rd

  • In the examples the sum value is always isolated, with the remaining zero. It is always this way or there are exceptions ?

1 answer

3


I don’t know if this is the best way, but you can do it like this:

array = [{dia:2,turno: 'turno1',M:1,T:0,N:0},  {dia:2,turno: 'turno2',M:0,T:2,N:0},  {dia:2,turno: 'turno3',M:0,T:0,N:1},  {dia:3,turno: 'turno1',M:122,T:0,N:0},  {dia:3,turno: 'turno2',M:0,T:21,N:0},  {dia:3,turno: 'turno3',M:0,T:0,N:12}]

resultado = []
array.map(function(a) {
     resultado[a['dia']] = resultado[a['dia']] || {dia: a['dia']}
     resultado[a['dia']][a['turno']] = (a['M'] + a['T'] + a['N'])
})

console.log(resultado.filter(String))

I believe there is not much to explain. The map() will execute the function for each array item, which will populate the resultado, based on the day of the current item, then it will add up all the M, T, N for such a shift.

  • Thank you for replying @Inkeliz, but look I don’t understand why console.log(resultado.filter(String))

  • @Daltonharvey O filter is to cut some results, in the case of those left as undefined.

  • @Isac Thanks for the explanation... understood now

Browser other questions tagged

You are not signed in. Login or sign up in order to post.