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

前端 未结 4 1221
执念已碎
执念已碎 2021-02-12 05:25

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 e

相关标签:
4条回答
  • 2021-02-12 06:06

    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);

    0 讨论(0)
  • 2021-02-12 06:13

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

    0 讨论(0)
  • 2021-02-12 06:13

    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 讨论(0)
  • 2021-02-12 06:19

    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);

    0 讨论(0)
提交回复
热议问题