Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return index of nearest values in an array

Tags:

javascript

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 }

like image 900
rnrneverdies Avatar asked Sep 15 '14 18:09

rnrneverdies


1 Answers

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))
like image 146
kornieff Avatar answered Sep 29 '22 21:09

kornieff