0

I have 2 arrays =

var arr1 = ['20', '35', '50'];

var arr2 = ['+5', '-5', '+10'];

I need to add the elements vertically:

var finalArr = ['25', '30', '60'];

I tried:

var arr1 = ['20', '35', '50']
var arr2 = ['+5', '-5', '+10'];
for (var i = 0; i < arr1.length; i++) { 
var arr1 = arr1[i] + arr2[2];
}
1
  • Do the arrays need to be composed of string representations of numbers, or can they be arrays of numbers? That determines the type of answer is appropriate. Commented Sep 16, 2015 at 1:08

2 Answers 2

2

You need to add the corresponding elements of the array, using the same index. You also need to assign the results either into the associated index in arr1, or into a new array. Also, the array elements need to either be numbers in the first place, or you need to convert them into numbers within the loop. With them both being strings, you'll just concatenate them instead of adding them.

var arr1 = [20, 35, 50], arr2 = [5, -5, 10], finalArr = [];
for (var i = 0; i < arr1.length; i++) {
    finalArr.push(arr1[i] + arr2[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

One easy way to do this is by using eval creatively, like so:

var arr1 = ['20', '35', '50'];

var arr2 = ['+5', '-5', '+10'];

var result = arr1.map(function(e,i){
    return eval(e+arr2[i]);
});

Or if you don't want to use eval then you can do simply parse string, parsing to int doesn't ignore the sign.

arr1.map(function(e,i){
    return +(e)+(+arr2[i]);
});

http://jsfiddle.net/mjbwbzof/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.