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

106
Visualizações
Compare key and get neatest min key and it's value in JavaScript array of object

I have JS object like this

    {
        "100": {.. data },
        "200": {.. data },
        "500": {.. data },
        "1000": {.. data }
        /* so on */
    }

How to search key with any number like

  • if search number is between 0 to 99 then it will return false,
  • if search number is between 100 to 199 then it will return key 100 and its value
  • if 500 to 999 then return key 500 and its value
  • if 1000+ then key as 1000 and its value

here is my code

function find(num, obj) 
{
  let keys = Object.keys(obj);
  
  result = keys.concat(Number.MAX_SAFE_INTEGER).filter(key => {
     return num <= key;
  }).shift();

  if(result === Number.MAX_SAFE_INTEGER) {
     result = keys.pop();
  }
  return result;
}


console.log( find(125, data) )

it's returning 200 instead of 100

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A simple approach here is to sort the keys in descending order, then find the first key that target larger than it.

function findNearestMinObj(obj, target) {
  const sortedKeys = Object.keys(obj).map(d => Number(d)).sort((a, b) => b - a)
  const key = sortedKeys.find(k => target >= k)
  if (key === undefined) return false
  return {
    key,
    value: obj[key]
  }
}

const data = {
  100: "one hundred",
  200: "two hundred",
  300: "three hundred",
  400: "four hundred",
  500: "five hundred",
  1000: "one thousand",
}

console.log(`123: ${JSON.stringify(findNearestMinObj(data, 123))}`)
console.log(`456: ${JSON.stringify(findNearestMinObj(data, 456))}`)
console.log(`1234: ${JSON.stringify(findNearestMinObj(data, 1234))}`)
console.log(`99: ${JSON.stringify(findNearestMinObj(data, 99))}`)
console.log(`0: ${JSON.stringify(findNearestMinObj(data, 0))}`)

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