Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

81
Visualizações
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:

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

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda