Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map and match ranges in javascript

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

like image 666
David Hellsing Avatar asked May 28 '26 01:05

David Hellsing


1 Answers

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

like image 118
Marcelo De Zen Avatar answered Jun 01 '26 08:06

Marcelo De Zen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!