JS对象数组,按时间戳分组值

时间:2019-04-15 11:16:56

标签: javascript arrays sorting

我有一些对象,如:

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小时。 我需要显示开始和结束真值的时间,从假值开始应分别设置时间:

实验次数:次: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')));

2 个答案:

答案 0 :(得分:1)

您可以为值添加时间戳,并构建atart和结束项目,将这些项目加入并加入结果。

var array = [{ 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 }],
    result = array
        .reduce((r, b, i, { [i - 1]: a }) => {
            if (!b.value) return r;
            if (a && a.value) {
                r[r.length - 1][1] = b.timestamp.slice(11, 16);
            } else {
                r.push([b.timestamp.slice(11, 16)]);
            }
            return r;
        }, [])
    .map(a => a.join('-'))
    .join(', ');

console.log(result);

答案 1 :(得分:0)

无耻的插件:您可以使用我的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"></script>
<script src="https://cdn.jsdelivr.net/npm/moment"></script>