Home > database >  How to zip two arrays into one array which every array contains another array
How to zip two arrays into one array which every array contains another array

Time:09-15

I would like to "zip" values from two arrays into 1 array. E.g. I got an array with titles: ['Cukier biały premium', 'second item'] and the second array with quantity of the titles [1, 999] i.e. Cukier biały premium quantity is 1 and should be in array and so on.. and I'd like to get an array with values of these two arrays from index[0] and so on. But the problem is that inside this two arrays are more arrays inside: I got

 const productTitles = order.map((item) => item.productTitle);
  const productQuantity = order.map((item) => item.quantity);
  console.log('product titles', productTitles); // output:  [Array(2), Array(3)] 
  console.log('product quantities', productQuantity); // output: [Array(2), Array(3)]

  const merged = productTitles.map((title, i) => [title, productQuantity[i]]);

enter image description here

How to Zip the merged array to got data like: ["Cukier biały premium", 1] and ["second item", 999] in one array and so this is order 1 () that I can .map over and display it in orders page? the second array (order 2) should contain an array of ["Cukier biały premium", 1], [Cukier czarny, 1], [Cukier amerykanski, 1]

Tried like this but got an array of [undefined, undefined]

const merged2 = productTitles.map((title, i) => {
    productQuantity.map((quantity, index) => {
      [title[i], quantity[index]];
    });
  });

CodePudding user response:

You had the right basic idea. Issue you had is you were mixing up the indexes. And you were not returning anything in the map calls.

const productTitles = [
  ['a', 'aa'],
  ['b', 'bb'],
];

const productQuantity = [
  [1, 11],
  [2, 22],
];

const merged2 = productTitles.map((row, rowIndex) =>
  row.map((value, columnIndex) => [value, productQuantity[rowIndex][columnIndex]]));

console.log(merged2);


// Use flatMap if you do not want a nested array

const mergedFlat = productTitles.flatMap((row, rowIndex) =>
  row.map((value, columnIndex) => [value, productQuantity[rowIndex][columnIndex]]));

console.log(mergedFlat);

CodePudding user response:

Short solution but not performant for big list since we call productQuantity.flat() on every iteration:

productTitles.flat().map((p, i) => [p, productQuantity.flat()[i]])

CodePudding user response:

have your tried destructuring the array

  • Related