计算数组中的元素多个值

时间:2018-06-01 03:10:20

标签: javascript arrays filter count reduce

我在下面有以下JSON对象。以一种信息显示方式计算班次和部门的有效方式是什么:

shift 1: 10
shift 2: 15

shift 1 & Carton-Pack: 5
shift 1 & Picking: 3
etc.

这只是我对javascript的新手,我担心我可能会过度复杂化。

JSON对象

[
{"shift":2,"department":"Pallet-Pack"},
{"shift":1,"department":"Carton-Pack"},
{"shift":2,"department":"Carton-Pack"},
{"shift":1,"department":"Picking"},
{"shift":1,"department":"Carton-Pack"},
{"shift":1,"department":"Carton-Pack"},
{"shift":2,"department":"Picking"},
{"shift":3,"department":"Inventory"},
{"shift":1,"department":"Carton-Pack"},
{"shift":1,"department":"Receiving"},
{"shift":3,"department":"Equipment"},
{"shift":2,"department":"Receiving"},
{"shift":1,"department":"Picking"},
{"shift":1,"department":"Picking"},
{"shift":2,"department":"Carton-Pack"},
{"shift":2,"department":"Carton-Pack"},
{"shift":1,"department":"Receiving"},
{"shift":1,"department":"Returns"},
{"shift":1,"department":"Receiving"},
{"shift":1,"department":"Picking"},
{"shift":2,"department":"Receiving"},
{"shift":1,"department":"Pallet-Pack"},
{"shift":2,"department":"Picking"},
{"shift":1,"department":"Carton-Pack"}]

1 个答案:

答案 0 :(得分:0)

抱歉,我在手机上这样做并且无法检查,但它是关于我该怎么做的。

counts_by_shift = shifts.reduce((counts, s) => {
  if (!counts[s.shift]) {
    counts[s.shift] = {}
    counts[s.shift]._total = 0
  }
  if (!counts[s.shift][s.department]) counts[s.shift][s.department] = 0
  counts[s.shift][s.department]++
  counts[s.shift]._total++
  return counts
}, {})
console.log(JSON.stringify(counts_by_shift))