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

155
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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