如何在javascript中逐元素地从一个数组中减去另一个数组

71

如果我有一个数组A = [1, 4, 3, 2]B = [0, 2, 1, 2],我想返回一个新数组(A-B),其值为[1, 2, 2, 0]。在JavaScript中,最有效的方法是什么?


2
一个声望如你的用户应该知道在问题中分享努力的重要性。Stack Overflow是为了帮助解决你的问题,而不是为你的需求提供解决方案。 - Rajesh
试一下, https://dev59.com/aXM_5IYBdhLWcg3w3nbz - Anand
请尝试此链接:https://dev59.com/aXM_5IYBdhLWcg3w3nbz - Anand
4
例子中计算出的数值是错误的。应该是[1,2,2,0]而不是[0,2,2,0]。 - Adrian Dymorz
7个回答

125

如果你想找到两个集合之间的差集,也就是说,你想要A中所有不在B中的元素:

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

如果您想要求解 A 和 B 中对应元素之间的算术差异,请参考其他发布的答案。


2
请将以下与编程相关的内容从英文翻译成中文。只返回翻译后的文本:解释会很有帮助! - platinums
7
这个解决方案过滤数组 A 并返回一个包含数组 A 中所有不包含在 B 中的元素的数组,从而有效地将 B 从 A 中减去。 - John
84
这不是rrbest所要求的。 - Melroy van den Berg
1
@danger89,我同意你的看法。如果两个数组长度相同,则以下是一个简单的解决方案:ArrA.map((n, i) => n - ArrB[i]); - Andrii Gordiichuk
39
通过搜索"subtract array",我实际上是在寻找这个答案,哈哈。谢谢。 - Sergiy Ostrovsky

46

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


2
let x = a.map((item, index) => item - b[index]); - Winters

8

For 简单高效,永远如此。

点击此处查看: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);


3
两个数组的长度应该相同,否则可能会出现问题。或者在处理之前先进行处理。 - Avnesh Shakya
@AvneshShakya 是的。两个数组应该是相同的,这就是所要求的。 - Sankar
对我来说,上面的 JsPerf 并没有显示 for 循环最快。所以我自己做了一个:https://jsperf.com/for-loop-vs-map-vs-for-each-kce,并发现对于大 n,for 循环要快得多。 - KCE

3
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]

这里的map函数会对第一个数组中的每个数字进行减法操作。

注意:如果两个数组长度不同,这种方法将无法使用。


1
目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

2

使用ES6的一行代码来处理长度相等的数组:

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

v = 值,i = 索引


1

如果您想覆盖第一个表中的值,只需使用数组的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);


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

时间复杂度为O(n),您还可以将其与大量数组进行比较。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接