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

238
Visualizações
How to map or zip a simple array to an array of arrays in JS with vanilla JS

I have an array of food categories, and I want to pair each category to a list of product codes that are in an array of arrays.

const categories = [ "dairy", "fruit", "breakfast", "frozen" ];  
const codes = [['2340', '89878', '9998'], ['89878'], ['987979', '984', '29898', '299'], ['0008', '2988'}]

categories and codes both have 10 elements each. How can I end up with ...

const onSale = {dairy:['2340', '89878', '9998'], fruit: ['89878'], breakfast:['987979', '984', '29898', '299'] , frozen: ['0008', '2988'}

Im a newbie, so Vanilla JS preferred.

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

0

You can use the second parameter passed in to the map function to know which index this element is at. Then pull the matching index from the other array. Since you want a resulting object, use fromEntries to wrap up the array that results from map.

const categories = [ "dairy", "fruit", "breakfast", "frozen" ];  
const codes = [['2340', '89878', '9998'], ['89878'], ['987979', '984', '29898', '299'], ['0008', '2988']];

const onSale = Object.fromEntries(
  categories.map((cat, i) => [cat, codes[i]])
);

console.log(onSale)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do it by reduce method, like this:

const categories = [ "dairy", "fruit", "breakfast", "frozen" ];  
const codes = [['2340', '89878', '9998'], ['89878'], ['987979', '984', '29898', '299'], ['0008', '2988']]
const onSales = categories.reduce((acc, key, index)=> {
    acc[key] = codes[index];
    return acc;
}, {});
console.log(onSales)

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