Reputation: 83
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
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
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