Working in JavaScript, I have two arrays that I need to combine to generate a concatenation of all its elements, for example:
var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];
resultado = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"];
To do that I can think of 3 different methods: using the classic loop for
, using the method forEach
, or using the map
method, in the following ways:
for
var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];
var resultado = [];
for(var x = 0; x < array1.length; x++) {
for (var y = 0; y < array2.length; y++) {
resultado.push(array1[x] + array2[y]);
};
};
console.log(resultado);
forEach
var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];
var resultado = [];
array1.forEach(function(valor1) {
array2.forEach(function(valor2) {
resultado.push(valor1 + valor2);
});
});
console.log(resultado);
map
var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];
var resultado = [];
array1.map(function(valor1) {
array2.map(function(valor2) {
resultado.push(valor1 + valor2);
});
});
console.log(resultado);
The three methods cross both arrays and with the three I get the same result (as you can see in the examples above). Now my questions:
- What are the advantages / disadvantages of each method?
- Is there one that should be used on the others, or depending on the situation?
- Is there a method that does something similar and is better (eg, more efficient or faster)