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

189
Visualizações
ES9 javascript update array of objects from other array of objects

I have an array containing carriers details:

const carrier=[
                {"carrier_code":"ups","items":0,"printable":0},
                {"carrier_code":"dhl","items":0,"printable":0},
                {"carrier_code":"tnt","items":0,"printable":0}
              ];

Then another array containing orders:

const orders = [
                  {"order_id":"00101","carrier_code":"dhl","printable":0},
                  {"order_id":"00101","carrier_code":"ups","printable":1},
                  {"order_id":"00101","carrier_code":"dhl","printable":1},
                  {"order_id":"00101","carrier_code":"dhl","printable":1},
                  {"order_id":"00101","carrier_code":"ups","printable":1},
                  {"order_id":"00101","carrier_code":"ups","printable":0},
                  {"order_id":"00101","carrier_code":"ups","printable":1},
                  {"order_id":"00101","carrier_code":"ups","printable":1}
               ];

I want to update items and printable values in carrier in a way to have

carrier=[
            {"carrier_code":"ups","items":5,"printable":4},
            {"carrier_code":"dhl","items":3,"printable":2},
            {"carrier_code":"tnt","items":0,"printable":0}
        ];
          

I've been able to achieve a similar result using map/filter/reduce, but for a situation with one object and one array.

While for this situation I can only think to a nested forEach :

carriers.forEach(c =>
{
    orders.forEach(o =>
      {
          c.items+=o.carrier_code==c.carrier_code?1:0;
          c.printable+=o.carrier_code==c.carrier_code&&o.printable==1?1:0;
      }
    )
});
  
console.log(carriers)

But perhaps this is an ES6 solution

I was wondering that ES9 could offer a "better" solution,

Can somebody suggest an easier or more elegant way to achieve the same result?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

To reduce the computational complexity, first group the carrier by the carrier_code, then you can iterate over the orders and look up the match immediately (O(n) instead of O(n ^ 2)).

Object.fromEntries can be used to group the carriers, which is from ES2019.

const carrier=[{carrier_code:"ups",items:0,printable:0},{carrier_code:"dhl",items:0,printable:0},{carrier_code:"tnt",items:0,printable:0}],orders=[{order_id:"00101",carrier_code:"dhl",printable:0},{order_id:"00101",carrier_code:"ups",printable:1},{order_id:"00101",carrier_code:"dhl",printable:1},{order_id:"00101",carrier_code:"dhl",printable:1},{order_id:"00101",carrier_code:"ups",printable:1},{order_id:"00101",carrier_code:"ups",printable:0},{order_id:"00101",carrier_code:"ups",printable:1},{order_id:"00101",carrier_code:"ups",printable:1}];

const carrierByCode = Object.fromEntries(
  carrier.map(c => [c.carrier_code, c])
);
for (const order of orders) {
  const carrier = carrierByCode[order.carrier_code];
  carrier.items++;
  if (order.printable) carrier.printable++;
}
console.log(carrier);

about 4 years ago · Juan Pablo Isaza Relatório

0

Nothing in the spec that turns this into a single(ish) call, but you can certainly reduce that O(n * m) complexity to O(n + m) complexity by first bin-counting your orders, then assigning those counts to your carriers:

const counters = {};

// run your bin counting in O(n)
orders.forEach({carrier_code} => {
  if (counters[carrier_code] === undefined) {
    counters[carrier_code] = 0;
  }
  counters[carrier_code]++;
});

// And then assign those counts in O(m)
carriers.forEach(c => (c.items = counters[c.carrier_code]));
about 4 years ago · Juan Pablo Isaza Relatório

0

I would first count and sum the items i need and then assign them to corresponding carrier. This is what i would do:

const carrier = [
  { carrier_code: "ups", items: 0, printable: 0 },
  { carrier_code: "dhl", items: 0, printable: 0 },
  { carrier_code: "tnt", items: 0, printable: 0 }
];
const orders = [
  { order_id: "00101", carrier_code: "dhl", printable: 0 },
  { order_id: "00101", carrier_code: "ups", printable: 1 },
  { order_id: "00101", carrier_code: "dhl", printable: 1 },
  { order_id: "00101", carrier_code: "dhl", printable: 1 },
  { order_id: "00101", carrier_code: "ups", printable: 1 },
  { order_id: "00101", carrier_code: "ups", printable: 0 },
  { order_id: "00101", carrier_code: "ups", printable: 1 },
  { order_id: "00101", carrier_code: "ups", printable: 1 }
];

var counts = orders.reduce((p, c) => {
  if (!p.hasOwnProperty(c.carrier_code))
    p[c.carrier_code] = { items: 0, printable: 0 };
  p[c.carrier_code].items++;
  p[c.carrier_code].carrier_code=c.carrier_code;
  p[c.carrier_code].printable += c.printable;
  return p;
}, {});
carrier.forEach((e, index) => carrier[index] = counts[e.carrier_code] || carrier[index]);

console.log(carrier);

about 4 years ago · Juan Pablo Isaza 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