63

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?

Art
  • 453
  • 4
  • 12
rrbest
  • 1,619
  • 3
  • 14
  • 22
  • 4
    Possible duplicate of [What is the fastest or most elegant way to compute a set difference using Javascript arrays?](https://stackoverflow.com/questions/1723168/what-is-the-fastest-or-most-elegant-way-to-compute-a-set-difference-using-javasc) – jhpratt Jul 27 '17 at 05:37
  • 2
    A user with your rep should know the importance of sharing effort in question. SO is to get help for your problems and not solution for your requirements – Rajesh Jul 27 '17 at 05:55
  • Try this., https://stackoverflow.com/questions/1187518/javascript-array-difference – Anand Jul 27 '17 at 06:21
  • Try this link: https://stackoverflow.com/questions/1187518/javascript-array-difference – Anand Jul 27 '17 at 06:23
  • 4
    The caluclated values in the example are wrong. It should be [1,2,2,0] and not [0,2,2,0]. – Adrian Dymorz Feb 21 '20 at 19:29

7 Answers7

122

If you want to find the set difference between two sets, that is, you want all the elements of A that are not in B:

const A = [1, 4, 3, 2]
const B = [0, 2, 1, 2]
console.log(A.filter(n => !B.includes(n)))

If you want arithmetic differences between the elements of A and the corresponding elements of B, then please look to the other posted answers.

TMBailey
  • 557
  • 3
  • 14
Andrii Gordiichuk
  • 1,783
  • 1
  • 12
  • 10
44

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);
brk
  • 48,835
  • 10
  • 56
  • 78
8

For Simple and efficient ever.

Check here : JsPref - For Vs Map Vs forEach

var a = [1, 4, 3, 2],
  b = [0, 2, 1, 2],
  x = [];

for(var i = 0;i<=b.length-1;i++)
  x.push(a[i] - b[i]);
  
console.log(x);
Sankar
  • 6,908
  • 2
  • 30
  • 53
  • 3
    Both arrays length, suppose to be same. otherwise it can create a problem. Or handle it before. – Avnesh Shakya Jul 27 '17 at 06:19
  • @AvneshShakya Yes. Both array should be same and that's what asked. – Sankar Jul 27 '17 at 06:26
  • Strange, for me the JsPerf above doesn't show the for loop as fastest. So I made my own: https://jsperf.com/for-loop-vs-map-vs-for-each-kce and found that for large n the for loop is many times faster. – KCE Jun 16 '18 at 09:14
2

One-liner using ES6 for the array's of equal size in length:

 let subResult = a.map((v, i) => v - b[i]); // [1, 2, 2, 0] 

v = value, i = index

SridharKritha
  • 8,481
  • 2
  • 52
  • 43
2
const A = [1, 4, 3, 2]
const B = [0, 2, 1, 2]
const C = A.map((valueA, indexInA) => valueA - B[indexInA])
console.log(C) // [1, 2, 2, 0]

Here the map is returning the substraction operation for each number of the first array.

Note: this will not work if the arrays have different lengths

TOPKAT
  • 6,667
  • 2
  • 44
  • 72
h13o
  • 56
  • 2
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 23 '21 at 09:35
1

If you want to override values in the first table you can simply use forEach method for arrays forEach. ForEach method takes the same parameter as map method (element, index, array). It's similar with the previous answer with map keyword but here we are not returning the value but assign value by own.

var a = [1, 4, 3, 2],
  b = [0, 2, 1, 2]
  
a.forEach(function(item, index, arr) {
  // item - current value in the loop
  // index - index for this value in the array
  // arr - reference to analyzed array  
  arr[index] = item - b[index];
})

//in this case we override values in first array
console.log(a);
0
function subtract(operand1 = [], operand2 = []) {
console.log('array1', operand1, 'array2', operand2);
const obj1 = {};

if (operand1.length === operand2.length) {
    return operand1.map(($op, i) => {
        return $op - operand2[i];
    })
}
throw new Error('collections are of different lengths');
}

// Test by generating a random array
function getRandomArray(total){
const pool = []
for (let i = 0; i < total; i++) {
    pool.push(Math.floor(Math.random() * total));
}

return pool;
}
console.log(subtract(getRandomArray(10), getRandomArray(10)))

Time Complexity is O(n) You can also compare your answer with a big collection of arrays.