Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!