Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

207
Vistas
Sorting keys from and object based on the difference in value Javascript?
let scores = {
  A: 30,
  B: 40,
  C: 35,
  D: 90
}



function getScores(students) {

  let result = []
  let keys = Object.keys(scores)
  let difference = 0
  for (let i = 0; i < keys.length; i++) {
    console.log('key', keys[i])
    if (scores[keys[i]] < scores[keys[i + 1]]) {
      difference = scores[keys[i + 1]] - scores[keys[i]]
      if (difference <= 15) {
        result.push(keys[i])
        result.push(keys[i + 1])
        console.log('result', result)
      }
      console.log('>>>', difference)
    } else {
      difference = scores[keys[i]] - scores[keys[i + 1]]
      if (difference <= 15) {
        if (!result.includes(keys[i])) {
          result.push(keys[i])
        }
        result.push(keys[i + 1])
        console.log('result', result)
      }

    }
    if (!result.includes(keys[i])) {
      result.push([keys[i]])
    }
    console.log('<<<', difference)
  }

}

getScores(scores)

I'm trying to group these into an array based on a condition that the value is less than 15. If a key and the next key have a difference less than 15 then they should be pushed to the results array. This works some what in the code I have. When run I get result = ['A', 'B', 'C'] What I'm trying to get is result = [['A', 'B', 'C'], ['D']] so A B and C are 15 or less so they are in one nested array and D is in a separate array. I realize this is probably less than optimized code. Looking for any suggestions. Thanks

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Sounds like a job for reduce.

You can store the object keys in a variable, then reduce over the array. In the reducer function, check whether the value of the property after the current has a score difference of less than 16, and if so, push the current item to the last array in the accumulator array. Otherwise, push a new array with only the current item.

let scores = {A: 30, B: 40, C: 35, D: 90};

const keys = Object.keys(scores)
const result = keys.reduce((a, b, i) => {
  if (scores[b] - scores[keys[i + 1]] <= 15 && a[a.length - 1]) {
    a[a.length - 1].push(b)
  } else {
    a.push([b])
  }
  return a;
}, [])

console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You should also take care of negative values so use Math.abs.

let scores = { A: 30, B: 40, C: 35, D: 90 };

const result = [];

Object.entries(scores).reduce(
  ([previousKey, previousValue], [key, value]) => {
    if (result.length === 0)
      result.push([previousKey]);
    if (Math.abs(previousValue - value) <= 15)
      result[result.length - 1].push(key);
    else
      result.push([key]);
    return [key, value];
  }
);

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

let scores = {
  A: 10,
  B: 40,
  C: 90,
  D: 80,
  E: 20,
  F: 10,
  G: 100,
  H: 95
}

let sorted = Object.fromEntries(
    Object.entries(scores).sort(([,a],[,b]) => b-a)
  )
let finalResult = []

function groups(students){
const keys = Object.keys(sorted)
const result = keys.reduce((a, b, i) => {
   
  if (sorted[b] - sorted[keys[i+1]] <= 15 && !a.includes(b)) {
    a.push(b)
    a.push(keys[i+1])
  }  
 if(sorted[b] - sorted[keys[i+1]] > 15){
   if(!a.includes(b))a.push(b)
   if(!finalResult.includes(a))finalResult.push(a)
    a = []
      
  }
 if(!finalResult.includes(a))finalResult.push(a)
 return a
}, [])
  console.log(finalResult)
}

This can probably be simplified in some way but it did get the job done.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda