1

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

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

3 Comments

I like the solution, what is the css for?
@sm3sher, it is for a larger console.log window. you may remove the css and look what's happening.
Oh now I see it, Grüße aus Düsseldorf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.