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

178
Vistas
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 Respuestas
Responde la pregunta

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