Working in JavaScript, I have two arrays that I need to combine to generate a concatenation of all their 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 method map
, 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);
All three methods traverse both arrays and with all 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 over the others? Or depending on the situation?
- Is there a method that does something similar and is better (eg: more efficient or faster)
It's a pretty generic question. The classic
for
and the most modernforEach
are basically the same. In fact,forEach
it was born as a more modern alternative to the classicfor
(as in most languages). The use offor
is more reasonable for doing a given number of iterations, while itforEach
is for traversing collections. The advantage offor
is that it is quite fast compared toforEach
(although this one is not slow).The answer is always it depends. As I said in the previous point,
for
andforEach
although they can be used for the same things, the last one is mainly intended to traverse collections (hence its name).Map
, on the other hand, is intended to iterate over a collection but with the goal of operating on that collection to return a new one from it. This algorithm works the same in languages like Java.To answer this question we can make a small benchmark comparing the different structures:
performance test
This simple performance test yields interesting results. It seems to
map
be faster than Gecko than Webkit by a considerable difference.forEach
Conclusions
The latest versions of Firefox , Chrome and Edge , return the following:
Map
it is faster inGecko
than in all engines.for
It is the fastest structure of all.for in
it is the slowest structure of all.forEach
is faster thanmap
inWebkit
andChakra
.Chakra
It is the longest taking among the engines.for of
takes about the same time asforEach
.Obviously these results can vary between versions of engines / browsers, but I think the results are radical between them.