[英]How do I sum the elements of an arbitrary number of arrays with different lengths in Javascript?
雖然下面的代碼將滿足添加兩個不同長度的數組,但我如何修改它以接受任意數量的數組作為參數,例如 ([1, 2, 3], [4, 5], [6 ]) 將返回一個 [11, 7, 3] 的數組?
const addTogether = (arr1, arr2) => {
let result = [];
for (let i = 0; i < Math.max(arr1.length, arr2.length); i++) {
result.push((arr1[i] || 0) + (arr2[i] || 0))
}
return result
}
使用嵌套數組,並循環遍歷數組而不是硬編碼兩個數組變量。
您可以使用arrays.map()
獲取所有長度,以便計算最大長度。 和arrays.reduce()
總結每個數組中的一個元素。
const addTogether = (...arrays) => { let result = []; let len = Math.max(...arrays.map(a => a.length)); for (let i = 0; i < len; i++) { result.push(arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0)); } return result } console.log(addTogether([1, 2, 3], [4, 5], [6]));
與其使用要求您知道每個數組長度的for
循環,不如嘗試使用不知道的東西。 例如 - while
循環。
使用虛擬變量遞增並為每個數組重置它,並將循環終止的條件設置為 - arr[i] === null
。
您可以在函數內使用參數對象。
arguments
是一個可在函數內部訪問的類數組對象,其中包含傳遞給該函數的參數的值。
const addTogether = function () { const inputs = [...arguments]; const maxLen = Math.max(...inputs.map((item) => item.length)); const result = []; for (let i = 0; i < maxLen; i ++) { result.push(inputs.reduce((acc, cur) => acc + (cur[i] || 0), 0)); } return result; }; console.log(addTogether([1,2,3], [4,5], [6]));
解決方案:
const addTogether = (...args) => { let result = []; let max = 0; args.forEach((arg)=>{ max = Math.max(max,arg.length) }) for(let j=0;j<max;j++){ result[j]= 0 for (let i = 0; i < args.length; i++) { if(args[i][j]) result[j]+= args[i][j] } } return result } console.log(addTogether([1, 2, 3], [4, 5], [6]))
輸出:[ 11, 7, 3 ]
使用rest param syntax
接受任意數量的參數。 按長度降序對外部數組進行排序。 通過使用解構賦值將內部數組的第一個和其余部分分開。 最后使用Array.prototype.map()
遍歷第一個數組,因為它是最大的數組,並使用Array.prototype.reduce()
方法求和。
const addTogether = (...ar) => { ar.sort((x, y) => y.length - x.length); const [first, ...br] = ar; return first.map( (x, i) => x + br.reduce((p, c) => (i < c.length ? c[i] + p : p), 0) ); }; console.log(addTogether([1, 2, 3], [4, 5], [6]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.