Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add based on array key

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading