你好,我是编程新手,我偶然发现了两个数组中按日期对数组数据进行分组的方法。
这是我的数组:
header = [
{"2019-04-22": "Sun, Apr 22, 2019"},
{"2019-04-21": "Sat, Apr 21, 2019"},
]
body = [
{"2019-04-22": "doing customer support”},
{"2019-04-22": "reply to emails"},
{"2019-04-21": "send message to customers"},
]
如何将数组分组为一个数组,如下例所示
combinearray = {
"2019-04-22": [
"Sun, Apr 22, 2019",
"doing customer support",
"reply to emails",
],
"2019-04-21": [
"Sat, Apr 21, 2019",
"send message to customers",
],
}
按日期对两个数组数据进行分组对我来说似乎完全不是一件容易的事,我是 javascript 编程的初学者。如果有任何答案,我将不胜感激。
最佳答案
您可以按照以下步骤进行操作:
- 首次使用
concat()
组合两个数组,即header
和body
- 然后使用
reduce()
在那上面。并将空对象作为第二个参数(累加器的初始值)传递。 - 在
reduce()
回调中使用Object.keys()[0]
获取日期。 - 如果日期不是累加器的键,则检查日期是否设置为空
[]
。 - 使用
push()
将元素添加到数组。
注意:这不会删除对header
和body
中真实对象的引用。
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a)
return ac;
},{})
console.log(res)
然而,正如评论中提到的,不需要有带键的对象。只需简单地排列该键的值就足够了。对于 push()
a[key]
而不是 a
。
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a[key])
return ac;
},{})
console.log(res)
关于javascript - 如何将两个javascript数组合并为一个并按日期分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55877153/