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
},
]
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))