Having trouble subtracting two variables(with arrays).

I have been looking online for the solution since yesterday and maybe one of you fine people can help me out. I have two arrays

var numbers = [15, 100, 101, 52, 75, 89, 90]; var subNums = numbers.map(function (value) { return value % 5; });

One is just a list of random numbers and the other is just the remainder of that list when divided by 5. I would like to be able to subtract "Subnums" from "numbers" and store the answer into another variable. No matter how I try and set this up I get NaN. Any help would be greatly appreciated.
(also if you can explain what you're doing that would be great!)

Posted Sep 16, 2016, 7:54 PM UTC

03
ivansvlv•

Hi friend, it's quite easy. Array methods like - map, forEach - provide a second parameter to a callback function which is index of the current element.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

So if I understood your problem correctly here is a code to subtract one array from another that can be written like this:

var subtractedArray = numbers.map(function(element, index) {
    // subtract element from "subNums" at the same index as current element in "numbers" from current element
    return element - subNums[index];
});

here is a small test from Chrome console:

var numbers = [15, 100, 101, 52, 75, 89, 90];
var subNums = numbers.map(function (value) { return value % 5; }); 
numbers
[15, 100, 101, 52, 75, 89, 90]
subNums
[0, 0, 1, 2, 0, 4, 0]
var subtracted = numbers.map(function(element, index) {
      return element - subNums[index];
});
subtracted
[15, 100, 100, 50, 75, 85, 90]
2
orebotOP•

thank you very much for the help. Also thank you for the link.

2
ivansvlv•

You are welcome, have fun!

1