0

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
 },
]
ScreamoIsDead
  • 157
  • 1
  • 1
  • 13
  • The result of the .sort() function determines the order. [See here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description) The idea is to use a function that returns -1 if the first object's color is red, returns 1 if the second object's color is red, and a > b otherwise. Try to solve this yourself. –  Jan 27 '22 at 10:21

1 Answers1

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))
Konflex
  • 465
  • 3
  • 11
  • How can i tell it to sort implicit by the color value? The colors are dynamically generated so i will need to tell the code i want you to sort the array with the color i tell it to sort with – ScreamoIsDead Jan 27 '22 at 10:12
  • 1
    OP is specifically asking how to prioritize a certain color. –  Jan 27 '22 at 10:22
  • Sorry for the misunderstanding, here is my updated answer – Konflex Jan 27 '22 at 10:33
  • I found a sollution here where i could make it work! https://stackoverflow.com/a/70877161/15024992 – ScreamoIsDead Jan 27 '22 at 11:58
  • @ScreamoIsDead your question got closed while I was typing an answer you can view it here . https://stackoverflow.com/a/70878429/7670898 – Kthree Jan 27 '22 at 12:20