Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
Get matched range value from array javascript

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
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda