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

223
Visualizações
Best way to sort array based of different sets of data?
var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
             {value:"19",type:"Fruit"},{value:"71",type:"Animal"},
             {value:"12",type:"Fruit"},{value:"15",type:"Fruit"}, 
             {value:"11",type:"Plant"},{value:"10",type:"Fruit"}, 
             {value:"16",type:"Plant"}] 

What is the best/optimized way to sort this array such that I get all elements of type Fruit first and then the elements of type Animal (by picking elements from end of array).

expectedOutput = [{value:"10",type:"Fruit"}, 
             {value:"15",type:"Fruit"},{value:"12",type:"Fruits"},
             {value:"19",type:"Fruit"},{value:"13",type:"Fruit"},
             {value:"71",type:"Animal"},{value:"61",type:"Animal"}, 
             {value:"16",type:"Plant"},{value:"11",type:"Plant"}]

Note:- I don't need to sort it Alphabetically. It must be sort depending upon the specific type.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can store the order of the type properties in an array, then subtract the index of the type property when sorting to determine precedence:

const order = ["Fruits", "Animal"]

var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
             {value:"19",type:"Fruit"},{value:"71",type:"Animal"},
             {value:"12",type:"Fruit"},{value:"15",type:"Fruit"}] 

const sorted = array.sort((a,b) => order.indexOf(a.type) - order.indexOf(b.type))

console.log(sorted)

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