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?
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.
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.
const A = [1, 4, 3, 2] const B = [0, 2, 1, 2] console.log(A.filter(n => !B.includes(n)))
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With