Balajee Ks
Balajee Ks

Reputation: 359

How to subtract elements of two arrays and store the result as positive array in javascript?

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

Answers (6)

Nina Scholz
Nina Scholz

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

Andy
Andy

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 ]

DEMO

Upvotes: 3

birnbaum
birnbaum

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

ManoDestra
ManoDestra

Reputation: 6473

for (var i = 0; i < A.length; i++) {
    C[i] = Math.abs(A[i] - B[i]);
}

Upvotes: 1

LetterEh
LetterEh

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

Kuzeko
Kuzeko

Reputation: 1705

You can use the javascript function Math.abs()

C.map(Math.abs);

Upvotes: 5

Related Questions