What is the most effective to map ranges using Arrays in JavaScript?
I have this:
var def = [70,200,1000];
And an array of possible numbers, say:
var n = [23,45,74,120,240,800,1204,2000];
Now, how can I extract the closest value from n that matches the values from def?
In the example above, I would get [74,240,800]. I hope I make myself clear...
Here is a try. Iterate over def and n just once:
var nIndex = 0,
nlen = n.length,
prev,
next;
for(var i = 0, ilen = def.length; i < ilen && nIndex < nlen; i++) {
var current = def[i];
while (n[nIndex] < current && nIndex < nlen - 1) nIndex++;
next = n[nIndex];
prev = nIndex == 0 ? next : n[nIndex - 1];
result[i] = current - prev < next - current ? prev : next;
}
// values in def are larger than the greatest value in n
while (result.length < def.length) result.push(n[nlen-1]);
fiddle
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