Javascript 如何在javascript中从另一个数组中减去一个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45342155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:01:01  来源:igfitidea点击:

How to subtract one array from another in javascript

javascript

提问by rrbest

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 [0, 2, 2, 0]. What is the most efficient approach to do this in javascript?

如果我有一个数组A = [1, 4, 3, 2]并且B = [0, 2, 1, 2]我想返回一个带有 values 的新数组(A - B)[0, 2, 2, 0]。在 javascript 中执行此操作的最有效方法是什么?

回答by Andrii Gordiichuk

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

回答by brk

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

使用map方法 map 方法在它的回调函数中接受三个参数,如下所示

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

回答by Sankar

ForSimple and efficient ever.

For简单而高效。

Check here : JsPref - For Vs Map Vs forEach

检查这里: 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);

回答by Kamil Mikosz

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.

如果您想覆盖第一个表中的值,您可以简单地将 forEach 方法用于数组forEach。ForEach 方法采用与 map 方法相同的参数(元素、索引、数组)。它与之前使用 map 关键字的答案类似,但在这里我们不是返回值而是自己分配值。

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