首页 > 解决方案 > 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')));

标签: javascriptarrayssorting

解决方案


无耻的插件:您可以使用我的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>


推荐阅读