I have this:
var scores=[0.7, 1.05, 0.81, 0.96, 3.2, 1.23];
What's the more readable way to return the indexes of the nearest values to another variable?
For instance:
With variable = 1 Should return { low: 3, high: 1 }
Almost as simple but faster (O(n)) than sort:
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With