如果我有一个数组A = [1, 4, 3, 2]
和B = [0, 2, 1, 2]
,我想返回一个新数组(A-B),其值为[1, 2, 2, 0]
。在JavaScript中,最有效的方法是什么?
如果我有一个数组A = [1, 4, 3, 2]
和B = [0, 2, 1, 2]
,我想返回一个新数组(A-B),其值为[1, 2, 2, 0]
。在JavaScript中,最有效的方法是什么?
如果你想找到两个集合之间的差集,也就是说,你想要A中所有不在B中的元素:
const A = [1, 4, 3, 2]
const B = [0, 2, 1, 2]
console.log(A.filter(n => !B.includes(n)))
如果您想要求解 A 和 B 中对应元素之间的算术差异,请参考其他发布的答案。
ArrA.map((n, i) => n - ArrB[i]);
- Andrii Gordiichuk使用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);
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);
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
函数会对第一个数组中的每个数字进行减法操作。
注意:如果两个数组长度不同,这种方法将无法使用。
使用ES6的一行代码来处理长度相等的数组:
let subResult = a.map((v, i) => v - b[i]); // [1, 2, 2, 0]
v = 值,i = 索引
如果您想覆盖第一个表中的值,只需使用数组的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);
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)
,您还可以将其与大量数组进行比较。