Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
Compare la clave y obtenga la clave mínima más ordenada y su valor en la matriz de objetos de JavaScript

Tengo un objeto JS como este

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

Cómo buscar clave con cualquier número como

  • si el número de búsqueda está entre 0 y 99, devolverá falso,
  • si el número de búsqueda está entre 100 y 199, devolverá la clave 100 y su valor
  • si 500 a 999, devuelva la clave 500 y su valor
  • si 1000+ entonces clave como 1000 y su valor

aquí está mi código

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

está devolviendo 200 en lugar de 100

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Un enfoque simple aquí es ordenar las claves en orden descendente, luego encontrar la primera clave que tenga un objetivo más grande que ella.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!