Reputation: 359
Assume i have 2 arrays,
A=[1,2,3,4,5,6]
B=[9,8,7,5,8,3]
When I subtract the elements of the array,
C=[-8,-6,-4,-1,-3,3]
How can I get the result of the subtraction as
C=[8,6,4,1,3,3]
Upvotes: 1
Views: 4293
Reputation: 386680
A solution for the absolute difference. c = |a - b|
var a = [1, 2, 3, 4, 5, 6],
b = [9, 8, 7, 5, 8, 3],
c = a.map(function (v, i) { return Math.abs(v - b[i]); });
document.write('<pre>' + JSON.stringify(c, 0, 4) + '</pre>');
Upvotes: 0
Reputation: 63550
Using Math.abs
function absSubtract(arr1, arr2) {
return arr2.map(function (el, i) {
return Math.abs(el - arr1[i]);
});
}
absSubtract(A, B); // [ 8, 6, 4, 1, 3, 3 ]
Upvotes: 3
Reputation: 4946
Math.abs() is returning the absolute value of a number.
You could do something like
var A=[1,2,3,4,5,6]
var B=[9,8,7,5,8,3]
var C = [];
for(let i = 0; i < A.length; i++) {
C.push(Math.abs(A[i] - B[i]));
}
Upvotes: 2
Reputation: 6473
for (var i = 0; i < A.length; i++) {
C[i] = Math.abs(A[i] - B[i]);
}
Upvotes: 1
Reputation: 26696
C = A.map( (x, i) => x - B[i] ).map( x => Math.abs(x) );
Assuming that A
and B
are the same length.
Upvotes: 1