javascript - 对数组内的数组进行分组
问题描述
我正在尝试按 ID 对列表进行分组,然后在该新列表中我尝试在特定时间根据该 ID 对值列表进行分组。我已经按 id 分组。我无法弄清楚我需要做什么才能按持续时间分组。请提供任何帮助
const data = [
{
"name": "ted",
"id": "1",
"timestamp": 1512709024000
},
{
"name": "seth",
"id": "2",
"timestamp": 1512754631000
},
{
"name": "joe",
"id": "1",
"timestamp": 1512711000000
},
{
"name": "phil",
"id": "2",
"timestamp": 1512754583000
},
{
"name": "kane",
"id": "1",
"timestamp": 1512709065294
},
]
}
{
"result": {
"1": [
{
"duration":18273
"names": ["ted", "joe", "kane"],
"startTime": 1512709065294
}
]
}
}
到目前为止我的努力
const d= data;
const ids= data.reduce((ids, item) => {
const id= (ids[item.id] || [])
id.push(item);
ids[item.id] = id
return ids
}, {})
console.log('visitorIds',visitorIds)
解决方案
看一下这个:
const data = [
{"name": "ted","id": "1","timestamp": 1512709024000},
{"name": "seth","id": "2","timestamp": 1512754631000},
{"name": "joe","id": "1","timestamp": 1512711000000},
{"name": "phil","id": "2","timestamp": 1512754583000},
{"name": "kane","id": "1","timestamp": 1512709065294},
];
const visitors = (data) => {
const groupedData = data.reduce((acc, {id, name, timestamp}) => {
acc[id] = (acc[id])
? {...acc[id], names: [...acc[id].names, name], times: [...acc[id].times, timestamp]}
: {names: [name], times: [timestamp]};
const startTime = Math.min(...acc[id].times);
const finishTime = Math.max(...acc[id].times);
const duration = finishTime - startTime;
acc[id] = {...acc[id], duration, startTime};
return acc;
}, {});
Object.values(groupedData).forEach((obj) => delete obj.times);
return groupedData;
};
console.log(visitors(data));
// {
// '1': {
// names: [ 'ted', 'joe', 'kane' ],
// duration: 1976000,
// startTime: 1512709024000
// },
// '2': {
// names: [ 'seth', 'phil' ],
// duration: 48000,
// startTime: 1512754583000
// }
// }
推荐阅读
- c++ - 如何使用 Gradle 的 cpp-library 和 cpp-application 插件指定自定义 GCC/G++ 编译器位置?
- typescript - TypeScript 类型错误 - 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型
- ruby-on-rails - 如何在 Google App Engine Standard 中为 Ruby On Rails 项目设置 Stack Driver 日志级别?
- angular - Angular - 服务人员没有立即应用更新
- go - 如何在终止程序时错误地嵌入退出代码以使用?
- reactjs - ag-grid 反应 + flatpickr 反应
- java - 如何在地图中引用静态类以便调用它?
- java - 如何在 Eureka 服务器中过滤掉 Eureka 客户端?
- python - 如何在字典中加粗、下划线(HTML 中的内联样式)以显示在 Tkinter GUI 中的单个文本?
- lua - Pandoc Lua 过滤器将章节和部分包装在 div 中