I have the following code, just curious if there's a way to make it more efficient/elegant through array chaining?
var sortOrder = ["green", "blue", "red"];
var sortThis = [
{ color: "blue" },
{ color: "red" },
{ color: "blue" },
{ color: "red" },
];
sortThis.sort(function (a, b) {
return sortOrder.indexOf(a.color) - sortOrder.indexOf(b.color);
});
sortThis.map(function (e) {
switch (e.color) {
case "blue":
e.price = 20;
break;
case "red":
e.price = 10;
break;
case "green":
e.price = 50;
break;
}
});
console.log(sortThis);
First, I want to sort the sortThis array with the order of sortOrder, then according to the value of 'color', append the price according
The code above achieves what I want:
0: {color: 'blue', price: 20}
1: {color: 'blue', price: 20}
2: {color: 'red', price: 10}
3: {color: 'red', price: 10}
Just curious if there's a way to make this more efficient/elagent through array chaining array.map/using spread operator?
Thanks in advance