0

I would like to iterate through two arrays subtracting one arrays value from another and adding their specific difference values to an object. So for example I have:

var answer = [];
var boom = [1,2,3,4];
var other = [[1,2,3,4],
             [2,3,4,5],
             [6,7,8,9];

for(var i=0; i<other.length; i++) {
    for(var e=0; e<4; e++){
        answer[e] = boom[e] - other[i][e];
    }
}

This give me an output of:

Object {0: -5, 1: -5, 2: -5, 3: -5} 

Which is boom subtracted from the last array in other what I am looking for and I think I am very close to getting it is:

Object [{0: [ 0, 0, 0, 0]},
        {1: [-1,-1,-1,-1]},
        {2: [-5,-5,-5,-5]}];

You can see that it will add the results of each iteration of the second for loop to the object answer. How can I accomplish this?

2 Answers 2

1
for(var i=0; i<other.length; i++) {
    answer[i] = [];
    for(var e=0; e<4; e++){
        answer[i][e] = boom[e] - other[i][e];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to initialize answer as an object not an as array, also you need to create a new answer array representing each set of values in other

var answer = {};
var boom = [1, 2, 3, 4];
var other = [
    [1, 2, 3, 4],
    [2, 3, 4, 5],
    [6, 7, 8, 9]
];

for (var i = 0; i < other.length; i++) {
    var temp = answer[i] = {};
    for (var e = 0; e < 4; e++) {
        temp[e] = boom[e] - other[i][e];
    }
}

Demo: Fiddle

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.