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?

1
  • No you can't. Write a loop (e.g. forEach or for). Commented Aug 15, 2012 at 8:43

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Tested this one too and it works. There were many similar answers by others but this one was easiest for me to understand.
2

Give this a try:

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

4 Comments

no var i (implicitly creating a global var) and stackoverflow.com/questions/500504/…. -1 sorry.
Works great and kudos for the simplicity!
@Sonypackman even if you like the simplicity, there are reasons not to use for ... in with Arrays in js.
Okay I trust you are right. Sorry fin1te I'm removing the correct answer selection.
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);

Comments

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

Comments

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

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.