简体   繁体   English

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

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

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] .如果我有一个数组A = [1, 4, 3, 2]B = [0, 2, 1, 2]我想返回一个新数组 (A - B),其值为[1, 2, 2, 0] What is the most efficient approach to do this in javascript?在 javascript 中执行此操作的最有效方法是什么?

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

Use map method 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);

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

If you want to override values in the first table you can simply use forEach method for arrays forEach .如果您想覆盖第一个表中的值,您可以简单地将 forEach 方法用于数组forEach ForEach method takes the same parameter as map method (element, index, array). ForEach 方法采用与 map 方法相同的参数(元素、索引、数组)。 It's similar with the previous answer with map keyword but here we are not returning the value but assign value by own.它与之前使用 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);

One-liner using ES6 for the array's of equal size in length:对长度相等的数组使用 ES6 的单行:

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

v = value, i = index v = 值,i = 索引

const A = [1, 4, 3, 2]
const B = [0, 2, 1, 2]
const C = A.map((valueA, indexA) => valueA - B[indexA])
console.log(C)
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.时间复杂度为O(n)您还可以将您的答案与 arrays 的大集合进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM