javascript - JS对象数组,按时间戳分组值
问题描述
我有一系列对象,例如:
var arr =
[{timestamp: "2019-04-15T11:00:00.000Z", value:true},
{timestamp: "2019-04-15T12:00:00.000Z", value: false},
{timestamp: "2019-04-15T13:00:00.000Z", value: true},
{timestamp: "2019-04-15T14:00:00.000Z", value: true},
{timestamp: "2019-04-15T15:00:00.000Z", value: true},
{timestamp: "2019-04-15T16:00:00.000Z", value: false},
{timestamp: "2019-04-15T17:00:00.000Z", value: true},
{timestamp: "2019-04-15T18:00:00.000Z", value: true}...] etc
24 小时。我需要显示开始和结束真值的时间,从值 false 应该是单独的一组时间:
对于 exp.:时间:11、13-15、17-18。
是否可以像这个数组一样排序?
目前我得到这样的数组:时间:11、13、14、15、16、17、18。
const onValues = arr.filter(item => item.output === true );
const onValuesTimes = onValues.map(a => (moment(a.timestamp).format('HH:mm')));
解决方案
无耻的插件:您可以使用我的ts-iterable-functions库:该groupAdjacent
功能是为此而设计的
const {pp, groupAdjacent, _map, map, _count, _single, _first, _last, filter} =
tsIterableFunctions
var arr = [
{timestamp: "2019-04-15T11:00:00.000Z", value: true},
{timestamp: "2019-04-15T12:00:00.000Z", value: false},
{timestamp: "2019-04-15T13:00:00.000Z", value: true},
{timestamp: "2019-04-15T14:00:00.000Z", value: true},
{timestamp: "2019-04-15T15:00:00.000Z", value: true},
{timestamp: "2019-04-15T16:00:00.000Z", value: false},
{timestamp: "2019-04-15T17:00:00.000Z", value: true},
{timestamp: "2019-04-15T18:00:00.000Z", value: true}
]
const q=pp(
arr,
groupAdjacent(
x => x.value,
x => x,
(key,elements) => ({
key,
values : _map(elements, e => moment(e.timestamp).utc().hour())
})
),
filter(x => x.key), // == true
map(
x => `${ _first(x.values) }-${ _last(x.values) + 1 }`
)
)
console.log([...q])
<script src="https://cdn.jsdelivr.net/npm/ts-iterable-functions@2"></script>
<script src="https://cdn.jsdelivr.net/npm/moment"></script>
推荐阅读
- css - 旋转:abc ddeg;仅受 Firefox 支持,但添加浏览器前缀似乎也破坏了 Firefox
- next.js - nextjs:多个孩子被传递给了“x”的“href”,但只支持一个孩子
- python - 主循环运行太多次并在二十一点游戏中给出太多牌
- firebase - (RN) 可能未处理的 Promise Rejection (id: 0):推送通知
- r - 根据截止日期创建新列(来自另一列的日期)
- lambda - 是否可以为 Boost 变体容器创建 Boost multi_index MEM_FUN 密钥提取器?
- python - Pandas 有效过滤动态日期范围
- javascript - 在 Firebase v9 错误中使用 uploadString 监控上传
- javascript - 更改 html 和 CSS 中的背景颜色
- r - bnlearn 抛出变量 A 在 bnlearn 中不受支持(类型:字符)