0

I have one array which is named as range and one lookpup variable. Now I am trying to get the matched range value from my range array. I tried to reduce method but it gives me an unexpected ouput.

Actual output

  • My value is 51 then it returns me 100

Expected output

  • Ex 1 - My value is 51 it's between 0-100 it should return 0 Ex 2 - My value is 135 it's between 100-150 it should return 100

My code

var lookup = 51; 
var range = [0, 100, 150, 200, 300, 300.2];
let filtered = range.reduce((prev, curr) => Math.abs(curr - lookup) < Math.abs(prev - lookup) ? curr : prev);
console.log(filtered); //100

Not Working in this case

const lookup = 201; 
const range = [200, 250, 300, 0, 450, 898].reverse();
const result = range.find(num => num <= lookup);
console.log(result); //0
1
  • You need to clarify how your ranges are defined. Are they from one index to the next? so 0...450 if so then 200...250 is included in that range. If that is the case then do you want the first range it matches, or the smallest range? Voting to close until you add clarity.
    – pilchard
    Commented Oct 15, 2021 at 18:02

1 Answer 1

5

Your desired result is a single number from the range array, so you should use .find instead of .reduce. Iterate from the right, and return true for the first element being iterated over that's smaller than or equal to the lookup.

const lookup = 51; 
const range = [0, 100, 150, 200, 300, 300.2].reverse();
const result = range.find(num => num <= lookup);
console.log(result);

If the array isn't necessarily sorted first, then sort it.

const lookup = 201; 
const range = [200, 250, 300, 0, 450, 898].sort((a, b) => b - a);
const result = range.find(num => num <= lookup);
console.log(result);

4
  • 1
    It's working for me but can u please explain why we need to use reverse?
    – Amv
    Commented Oct 15, 2021 at 17:49
  • @Amv Because, to find the first number that's lower than the lookup, you need to start looking from the right, not the left. Commented Oct 15, 2021 at 17:49
  • @CertainPerformance Your solution is not working properly. I added the case in my question
    – Amv
    Commented Oct 15, 2021 at 17:59
  • It relies on the array being sorted (as does my answer)
    – pilchard
    Commented Oct 15, 2021 at 18:01

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.