-3

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.

cordovez
  • 71
  • 11

2 Answers2

1

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)
James
  • 20,957
  • 5
  • 26
  • 41
1

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)
Saeed Shamloo
  • 6,199
  • 1
  • 7
  • 18