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

181
Visualizações
Javascript Sort Array of objects by object property that exists in several objects

I have an array of products where several products can have the same color, and i want to be able to sort this array by the color value. How i would i achieve an Array sorting for example to display all products first that has the color property of "red"? Or any other color that i will tell the array to sort first by.

const arr = [
 {
 name: "T-shirt",
 color: "red",
 price: 20
 },
 {
 name: "Shoes",
 color: "yellow",
 price: 20
 },
 {
 name: "Pants",
 color: "red",
 price: 20
 },
 {
 name: "Cap",
 color: "yellow",
 price: 20
 },
 {
 name: "Skirt",
 color: "red",
 price: 15
 },
]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Like this you will sort your array by color, if you want to get the yellow color in first return 1 and red return 2 to have in position 2 etc:

const getRanking = (ele) => {
    if (ele.color == "red") return 2; 
    if (ele.color == "yellow") return 1;
 };

arr.sort((a,b) => getRanking(a) - getRanking(b))
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