I want to add the values of the same positions? Here's my fix:
var arr1 = ["1","2","3","4"];
var arr2 = ["2","1","3","4"];
The result has to be:
var NuevoArreglo = ["3","3","6","8"];
I hope the help.
I want to add the values of the same positions? Here's my fix:
var arr1 = ["1","2","3","4"];
var arr2 = ["2","1","3","4"];
The result has to be:
var NuevoArreglo = ["3","3","6","8"];
I hope the help.
You can try the following:
As an alternative, I'm going to show you how to do it using the
Array.prototype.map
.You should know that the method
map
is used to process an array and obtain another array but transformed by means of a function (which does the transformation); You may be interested to know that it is one of the essential methods for working with arrays, along withArray.prototype.reduce
which it is used to consolidate/summarize data arrays.The intention behind
map
is to transform each item into a new item, with this in mind... consider the following example.Explanation
.map(Number)
converts"1"
to1
(numeric data type).map( (item, ix) => item + Number(arr2[ix]) )
for each number, finds and converts the corresponding number ofarr2
and adds them..map( (item) => item.toString() )
one converts each number back to a string to get the result.Note: I have used several maps to better exemplify how they are used, it is not necessary to do it in so many steps, it can be done in a single execution:
Now..
If instead of strings, numbers work well for you, things are much simpler.
Hope this can help you.
Note: I find it more readable to use
map
than to use a loop typefor each
or similar control structures since it looks like a chain of functions and there aren't as many brackets. But it is a matter of taste.Try this way:
Here I leave you a
script
where you do the sum through a forEach, this way of doing it is contemplating the new EcmaScript 6.Notice the use of the
arr1.forEach
.Perhaps the easiest option is to use
Array.map()
:According to your question, the initial Arrays contain
String
s and you want to add them and convert them back toString
, according to the expected output you show in the question.By prefixing each variable with the symbol
+
we are saying to convert the variable to a number. And adding we+ ""
convert the final number added to String.Note that both lists must be the same size.