JSON:
{"blockHistory":[10, 12, 14, 17],
"hashrateHistory":[
{"hr":1,"time":9},
{"hr":2,"time":10},
{"hr":3,"time":11},
{"hr":4,"time":12},
{"hr":5,"time":13},
{"hr":6,"time":14},
{"hr":7,"time":15}
]
我想从blockHistory中获得每个值的hr,其中hashrateHistory中的时间是最大的时间<=blockHistory值。
这就是我所拥有的。我不知道如何获得最后一个HR
[{lastHr: .hashrateHistory[].hr, time: .blockHistory[]}] | sort_by(.time)
我想要的结果:
[
{
"lastHr": 2,
"time": 10
},
{
"lastHr": 4,
"time": 12
},
{
"lastHr": 6,
"time": 14
},
{
"lastHr": 7,
"time": 17
}
]
(.hashrateHistory | sort_by(.time)) as $hashrate
| .blockHistory | map(
. as $max_time
| $hashrate
| map(select(.time <= $max_time))[-1]
| {lastHr: .hr, time: $max_time}
)
对于块的每个元素,迭代排序/保存的哈希率。只选择最后一个匹配的元素,然后在块映射中创建一个对象。
这里有另一种方法,它在构建中间结果后使用group_by
.blockHistory as $b
| [ .hashrateHistory[] | .group = [ $b[] < .time ] ]
| group_by(.group)
| map(max_by(.time) | del(.group))
| sort_by(.time)
根据您最初的尝试,这包括最终的sort_by
,但可能没有必要。
在线试用!
这里有一个面向时间效率的解决方案,假设.blockHistory数组足够大且"有趣",可以抵消构建字典($dict(和按.time
排序.hashrateHistory数组的前期投资。
精确匹配的情况使用字典($dict(处理,另一种情况使用内置函数bsearch
进行二进制搜索:
.hashrateHistory as $hashrateHistory
| INDEX($hashrateHistory[]; .time) as $dict
| ($hashrateHistory | sort_by(.time) ) as $sorted
| ($sorted | map(.time)) as $sorted_time
| ($sorted | map(.hr)) as $sorted_hr
| .blockHistory
| map( . as $t
| $dict[$t|tostring]
| if . then {lastHr: .hr, time }
else (-2 - ($sorted_time | bsearch($t))) as $i
| {lastHr: $sorted_hr[$i], time: $t}
end )