Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!