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

154
Vistas
Find top 3 values entries in a sorted JavaScript dictionary?

I have a sorted dictionary with certain number of entries:

dict = {B:3, A:2, C:2, D:1, E:0, F:0...}

Are there any ways to filter the dictionary to find the entries with top 3 largest values while considering duplicated values so the output will be? :

output = {B:3, A:2, C:2, D:1}

Thanks for reading..

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

0

You could count distinct values with a Set and filter ordered entries for getting an object from it.

const
    object = { B: 3, A: 2, C: 2, D: 1, E: 0, F: 0 },
    result = Object.fromEntries(Object
        .entries(object)
        .sort(([, a], [, b]) => b - a)                         // just to be sure
        .filter((s => ([, v]) => s.add(v).size <= 3)(new Set))
    );
    
console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Maybe this can help you.

var dict = {
  B: 3,
  A: 2,
  C: 2,
  D: 1,
  E: 0,
  F: 0
};

// Create items array
var items = Object.keys(dict).map(function(key) {
  return [key, dict[key]];
});

// Sort the array based on the second element
items.sort(function(first, second) {
  return second[1] - first[1];
});

// Create a new array with only the first 3 items
let slicedArray = items.slice(0, 3);

//Return appropriate value
let dictSorted = slicedArray.reduce((a, x) => ({ ...a,
  [x[0]]: x[1]
}), {});
console.log(dictSorted);

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