eclipseIzHere
eclipseIzHere

Reputation: 83

how to subtract both array's [0] and [1] and so on

I have two arrays:

var array = [100,200,300,400];
var another = [50,100,150,200];

say I don't know how long the arrays are, but knows they are the same length. How do I subtract the respective elements?

Upvotes: 0

Views: 53

Answers (2)

Nitheesh
Nitheesh

Reputation: 20006

Try this

<!DOCTYPE html>
<html>

<body>

    <script>
        var arra = [100, 200, 300, 400];
        var another = [50, 100, 150, 200];
        var diff = [];
        for (var i = 0; i < arra.length; i++) {
            diff[i] = arra[i] - another[i];
            console.log(diff[i]);
        }
    </script>
</body>

</html>

Just subtract the respective positions.

Upvotes: 0

Sandeep Nayak
Sandeep Nayak

Reputation: 4757

Use array.map like below

var arra = [100, 200, 300, 400];
var another = [50, 100, 150, 200];

var diff = arra.map(function(v, i) {
  return v - another[i]
});

console.log(diff)

Upvotes: 2

Related Questions