Home > Mobile >  Looping through two arrays to fill a two dimensionnal array
Looping through two arrays to fill a two dimensionnal array

Time:11-30

I work on Angular and use Typescript. I have two arrays array1 and array2 which I have parsed from an API.

A console.log on array1 looks like this :
enter image description here

A console.log on array2 looks like this :
enter image description here

I'd like to create an two dimensionnal array which would merge the two arrays one element by element (id 0 with id 0, id 1 with id 1, id 2 with id 2 and so on). To be clearer the result would be :

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

Would you have any ideas to realize that trick ?

Any help would be very appreciated, thank you !

CodePudding user response:

If both have the same length just use a map operator

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

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

CodePudding user response:

You can use Array.map() to give you the desired result, returning an element from arr1 and arr2 for each iteration.

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; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

`

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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

` enter code here

  • Related