Return index of nearest values in an array

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))


Slow (O(n*log(n)) and simple:

const nearest = (arr, val) => (sorted => (indexOfVal => ({
  lo: sorted[indexOfVal - 1],
  hi: sorted[indexOfVal + 1]
}))(sorted.indexOf(val)))([...arr, val].sort())


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))

Tags:

Javascript