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

232
Visualizações
Sort grouped array in asc/desc order

Can anyone assist in sorting the below array in ascending / descending order? The array is to be sorted based on the highest number in each grouping (grouped using brand). Numbers in each group are to be sorted as well:

original_array = [
  { brand: "Ford",   number: "1", },
  { brand: "BMW",    number: "1", },
  { brand: "BMW",    number: "5", },
  { brand: "BMW",    number: "20",},
  { brand: "Toyota", number: "10",}
];

desc_order = [
  { brand: "BMW",    number: "20",},
  { brand: "BMW",    number: "5", },
  { brand: "BMW",    number: "1", },
  { brand: "Toyota", number: "10",},
  { brand: "Ford",   number: "1", }
];

asc_order = [
  { brand: "Ford",   number: "1", },
  { brand: "Toyota", number: "10",},
  { brand: "BMW",    number: "1", },
  { brand: "BMW",    number: "5", },
  { brand: "BMW",    number: "20",}
];
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since the order of the brands in the output depends on maximum values in their group, I would suggest to first create an object that lists the maximum number per brand.

Then use that to sort by, using the following sequence of ordering:

  • First by the maximum value for the brand
  • When that is equal, by the name of the brand (since several brands could have the same maximum number)
  • When that is equal, by the number itself

Implementation:

const array = [ { brand: "Ford", number: "1", }, { brand: "BMW", number: "1", }, { brand: "BMW", number: "5", }, { brand: "BMW", number: "20", }, { brand: "Toyota", number: "10", } ];

// First collect the maximum values per brand as an aggregate:
const aggr = {};
for (let {brand, number} of array) { 
    aggr[brand] = Math.max(number, aggr[brand] ?? number);
}

// Ascending
array.sort((a, b) => aggr[a.brand] - aggr[b.brand] 
                  || a.brand.localeCompare(b.brand)
                  || a.number - b.number);
console.log(array);

// Descending
array.sort((a, b) => aggr[b.brand] - aggr[a.brand]
                  || b.brand.localeCompare(a.brand)
                  || b.number - a.number);
console.log(array);

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