Sony packman
Sony packman

Reputation: 840

Substract array from another array

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?

Upvotes: 1

Views: 219

Answers (5)

Warbo
Warbo

Reputation: 2736

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

Upvotes: 0

epoch
epoch

Reputation: 16615

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));​

Upvotes: 0

fin1te
fin1te

Reputation: 4351

Give this a try:

for (i in firstSet) {
    firstSet[i] -= secondSet[i];
}

Upvotes: 2

Blender
Blender

Reputation: 298364

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);

Upvotes: 0

Sune Trudslev
Sune Trudslev

Reputation: 974

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

Upvotes: 2

Related Questions