1

I have an array with eight values inside it. I have another array with the same amount of values. Can I simply substract these arrays from each other?

Here is an example:

var firstSet =[2,3,4,5,6,7,8,9]
var secondSet =[1,2,3,4,5,6,7,8]

firstSet - secondSet =[1,1,1,1,1,1,1,1] //I was hoping for this to be the result of a substraction, but I'm getting "undefined" instead of 1..

How should this be done properly?

Sony packman
  • 810
  • 2
  • 10
  • 21

5 Answers5

2

Like this:

var newArray = [];
for(var i=0,len=firstSet.length;i<len;i++)
  newArray.push(secondSet[i] - firstSet[i]);

Note that it is expected for secondSet to have the same number (or more) as firstSet

Sune Trudslev
  • 964
  • 6
  • 11
  • Tested this one too and it works. There were many similar answers by others but this one was easiest for me to understand. – Sony packman Aug 15 '12 at 09:18
2

Give this a try:

for (i in firstSet) {
    firstSet[i] -= secondSet[i];
}
fin1te
  • 4,289
  • 1
  • 19
  • 16
0

Element-wise subtraction should work:

var result = [];

for (var i = 0, length = firstSet.length; i < length; i++) {
  result.push(firstSet[i] - secondSet[i]);
}

console.log(result);
Blender
  • 289,723
  • 53
  • 439
  • 496
0
var firstSet = [2,3,4,5,6,7,8,9]
var secondSet = [1,2,3,4,5,6,7,8]

var sub = function(f, s) {
    var st = [], l, i;
    for (i = 0, l = f.length; i < l; i++) {
        st[i] = f[i] - s[i];
    }

    return st;
}

console.log(sub(firstSet, secondSet));​
epoch
  • 16,396
  • 4
  • 43
  • 71
0

What you're after is something like Haskell's "zipWith" function

"zipWith (-) xs ys", or in Javascript syntax "zipWith(function(a,b) { return a - b; }, xs, ys)" returns an array of [(xs[0] - ys[0]), (xs[1] - ys[1]), ...]

The Underscore.js library has some nice functions for this kind of thing. It doesn't have zipWith, but it does have "zip", which turns a pair of arrays xs, ys into an array of pairs [[xs[0], ys[0]], [xs[1], ys[1]], ...], which you can then map a subtraction function over:

_.zip(xs, ys).map(function(x) { return x[0] - x[1]; })

You may find this interesting https://github.com/documentcloud/underscore/issues/145

Warbo
  • 2,611
  • 1
  • 29
  • 23