簡體   English   中英

如何在 javascript 中按元素從另一個數組中減去一個數組

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

如果我有一個數組A = [1, 4, 3, 2]B = [0, 2, 1, 2]我想返回一個新數組 (A - B),其值為[1, 2, 2, 0] 在 javascript 中執行此操作的最有效方法是什么?

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

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

如果您想覆蓋第一個表中的值,您可以簡單地將 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);

對長度相等的數組使用 ES6 的單行:

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

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

時間復雜度為O(n)您還可以將您的答案與 arrays 的大集合進行比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM