js group objects in an array
js group objects in an array
js group objects in an array
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
https://www.consolelog.io/group-by-in-javascript/
https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects
https://atendesigngroup.com/blog/array-map-filter-and-reduce-js
solution ??? sort & reduce
https://repl.it/@xgqfrms/grouping-objects-in-array-by-timestamp
/**
* @authr xgqfrms
* @ description grouping-objects-in-array-by-timestamp
*/
let log = console.log;
const datas = [
{ msgId: 606896983568064500, text: "B", time: "2019/08/02 17:11", isSelf: true },
{ msgId: 606897486704189400, text: "A", time: "2019/08/02 17:13", isSelf: true },
{ msgId: 606892034444533700, text: "C", time: "2019/08/02 16:52", isSelf: false },
{ msgId: 606889698041045000, text: "D", time: "2019/08/02 16:42", isSelf: false },
{ msgId: 606866947376980000, text: "E", time: "2019/08/02 15:12", isSelf: false },
{ msgId: 606866947376970000, text: "G", time: "2019/08/01 5:12", isSelf: false },
{ msgId: 606866947376910000, text: "F", time: "2019/08/01 15:12", isSelf: false },
];
log(`src datas =`, JSON.stringify(datas, null, 4));
// m. s, ms
const fiveMinutes = 5 * 60 * 1000;
let result = datas
// timestamp
// asc
.sort((a, b) => new Date(a.time) - new Date(b.time))
.reduce((arr, obj, i, {[i - 1]: last}) => {
if (!last || new Date(obj.time) - new Date(last.time) > fiveMinutes) {
arr.push([obj]);
} else {
arr[arr.length - 1].push(obj);
}
return arr;
}, []);
log(`result =`, JSON.stringify(result, null, 4));
OK
[
[
{
"msgId": 606866947376970000,
"text": "G",
"time": "2019/08/01 5:12",
"isSelf": false
}
],
[
{
"msgId": 606866947376910000,
"text": "F",
"time": "2019/08/01 15:12",
"isSelf": false
}
],
[
{
"msgId": 606866947376980000,
"text": "E",
"time": "2019/08/02 15:12",
"isSelf": false
}
],
[
{
"msgId": 606889698041045000,
"text": "D",
"time": "2019/08/02 16:42",
"isSelf": false
}
],
[
{
"msgId": 606892034444533800,
"text": "C",
"time": "2019/08/02 16:52",
"isSelf": false
}
],
[
{
"msgId": 606896983568064500,
"text": "B",
"time": "2019/08/02 17:11",
"isSelf": true
},
{
"msgId": 606897486704189400,
"text": "A",
"time": "2019/08/02 17:13",
"isSelf": true
}
]
]
bug
https://repl.it/@xgqfrms/timestamp-group-bug
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/11303876.html
未经授权禁止转载,违者必究!