Reputation: 23
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
Upvotes: 1
Views: 37
Reputation: 386560
I would take sorting and getting a new array with new objects.
This approach does not mutate the given data. For order and prices take objects with the corresponding values.
const
order = { green: 1, blue: 2, red: 3 },
prices = { green: 50, blue: 20, red: 10 },
data = [{ color: "blue" }, { color: "red" }, { color: "blue" }, { color: "red" }],
result = data
.sort((a, b) => order[a.color] - order[b.color])
.map(o => ({ ...o, price: prices[o.color] }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1