循环遍历两个数组以填充二维数组

Looping through two arrays to fill a two dimensionnal array

我在 Angular 上工作并使用 Typescript。我有两个数组 array1array2,我从 API.

解析了它们

array1 上的 console.log 看起来像这样:

array2 上的 console.log 看起来像这样:

我想创建一个二维数组,它将两个数组一个元素一个元素地合并(id 0 和 id 0,id 1 和 id 1,id 2 和 id 2 等等)。更清楚的结果是:

[["Outils sali", "saunier"], ["outils elem", "outils trad"], ["outils trad", "outils sali"], .... ];

你有什么想法来实现这个技巧吗?

非常感谢任何帮助,谢谢!

如果两者的长度相同,只需使用映射运算符

array1 = []; // imagine filled
array2  = []; // imagine filled

let result  = array1.map((array1Value, index) => [array1Value, array2[index]]); 

您可以使用 Array.map() 为您提供所需的结果,每次迭代从 arr1 和 arr2 返回一个元素。

const arr1 = ['outils sali', 'outils elem', 'outils trad', 'matériel', 'produit'];
const arr2 = ['saunier','outils trad', 'outils sali', 'outils trad', 'matériel'];

const result = arr1.map((el, idx) => [el, arr2[idx]]);
console.log('Result:', result);
    
.as-console-wrapper { max-height: 100% !important; top: 0; }

`

const arr1 = ["outils sali", "outils elem", "outils trad", "materiel", "produit"];
const arr2 = ["saunier", "outils trad", "outils sali", "outils trad", "materiel"];

const newArray = []
let subArray = []

for(let i = 0; i<arr1.length; i++) {
    subArray = createArray(arr1[i],arr2[i])
    newArray.push(subArray)
}

function createArray(elem1,elem2) {
    return [elem1,elem2]
}

console.log(newArray)

` 在此处输入代码