如何在二维数组中根据时间戳查询对应的比特币价格数据?
时间戳查询对应价格的实现方案
针对Fetch API返回的固定格式[时间戳, 价格]二维数组,根据数据量和查询频率,有三种常用实现方式:
方案1:直接遍历查找(适用数据量<1000条,单次查询场景)
实现逻辑最简单,不需要提前处理数据,直接遍历数组匹配时间戳即可:
// data为接口返回的二维数组,timestamp为要查询的目标时间戳 function getPriceByTimestamp(timestamp, data) { const target = data.find(item => item[0] === timestamp) return target ? target[1] : null // 无匹配结果时返回null,可自定义默认值 } // 调用示例 const targetPrice = getPriceByTimestamp(1626332594721, priceData) // 返回结果:0.1343159833901
方案2:Map映射表查询(适用频繁查询场景,查询复杂度O(1))
如果需要多次查询,可以提前把二维数组转换为Map结构做映射,后续查询直接取值,效率最高:
// 接口返回数据后,仅执行一次构建映射表 const priceMap = new Map(priceData) // 任意次查询都直接取 const targetPrice = priceMap.get(1626332594721) ?? null
方案3:二分查找(适用超大数据量,且数据默认按时间排序的场景)
这类价格类时间序列接口返回的数据默认都是按时间戳升序/降序排列的,数据量超过1万条时用二分查找性能远高于普通遍历,时间复杂度为O(logn):
// 假设传入的sortedData为按时间戳升序排列的接口返回数据 function binarySearchPrice(timestamp, sortedData) { let left = 0 let right = sortedData.length - 1 while (left <= right) { const mid = Math.floor((left + right) / 2) const midTimestamp = sortedData[mid][0] if (midTimestamp === timestamp) return sortedData[mid][1] midTimestamp < timestamp ? left = mid + 1 : right = mid - 1 } return null } // 调用示例 const targetPrice = binarySearchPrice(1626332594721, priceData)
如果你的接口返回数据是按时间戳降序排列的,把代码中midTimestamp < timestamp的判断逻辑反过来即可。
内容的提问来源于stack exchange,提问作者J. De
相关产品推荐
相关产品推荐

