我有这个:
var scores=[0.7, 1.05, 0.81, 0.96, 3.2, 1.23];
将最接近的值的索引返回到另一个变量的更可读的方法是什么?
例如:
变量= 1应返回 { low: 3, high: 1 }
几乎比排序简单但快(O(n)):
const nearest = (arr, n) => arr.reduce((r, x) => ({
lo: ((x < n) && (x > r.lo) ? x : r.lo),
hi: ((x > n) && (x < r.hi) ? x : r.hi)
}), { lo: -Infinity, hi: Infinity })
const mapIndexOf = (obj, lookup) => Object.keys(obj).reduce(
(a, v) => ({ ...a, [v]: lookup.indexOf(obj[v]) }), {}
)
const scores = [0.7, 1.05, 0.81, 0.96, 3.2, 1.23]
console.log(mapIndexOf(nearest(scores, 1), scores))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句