Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract one array from another, element-wise, in javascript

Tags:

javascript

If i have an array A = [1, 4, 3, 2] and B = [0, 2, 1, 2] I want to return a new array (A - B) with values [1, 2, 2, 0]. What is the most efficient approach to do this in javascript?

like image 765
rrbest Avatar asked Jul 27 '17 05:07

rrbest


People also ask

How do you subtract two arrays of elements?

Description. C = A - B subtracts array B from array A by subtracting corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.

How do you subtract a value in JavaScript?

Similarly, we use the minus sign ( - ) to subtract numbers or variables representing numbers. We can also add and subtract with negative numbers and floats (decimals). One interesting thing to note and be aware of in JavaScript is the result of adding a number and a string.


2 Answers

const A = [1, 4, 3, 2]  const B = [0, 2, 1, 2]  console.log(A.filter(n => !B.includes(n)))
like image 58
Andrii Gordiichuk Avatar answered Sep 28 '22 11:09

Andrii Gordiichuk


Use map method The map method takes three parameters in it's callback function like below

currentValue, index, array 

var a = [1, 4, 3, 2],    b = [0, 2, 1, 2]    var x = a.map(function(item, index) {    // In this case item correspond to currentValue of array a,     // using index to get value from array b    return item - b[index];  })  console.log(x);
like image 25
brk Avatar answered Sep 28 '22 12:09

brk