[英]How to calculate sum of count of array elements of multiple arrays by order and limit?
[英]How to calculate the sum of multiple arrays?
我正在嘗試解決一個方程,在該方程中,我從索引后的數組列表中添加數字。
列表的每個數組都是隨機生成的 4 個數字的固定長度數組,如下所示:
const list = [
[2, 9, 1, 2],
[2, 3, 9, 4],
[4, 7, 8, 1]
]
所以我想要做的是從每個數組中獲取每個索引的每個數字的總和。 像這樣:
const list = [
[2, 9, 1, 2],
[2, 3, 9, 4],
[4, 7, 8, 1]
]
// expectedResult = [8, 19, 18, 7];
我怎樣才能做到這一點?
這是另一種方法,它在第一個數組上使用map() ,嵌套了一個reduce() ,生成相應列的總數。
const list = [ [2, 9, 1, 2], [2, 3, 9, 4], [4, 7, 8, 1] ]; const sums = list[0].map((x, idx) => list.reduce((sum, curr) => sum + curr[idx], 0)); console.log(sums);
.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}
const list = [ [2, 9, 1, 2], [2, 3, 9, 4], [4, 7, 8, 1], ]; const result = list.reduce((a, b) => a.map((c, i) => c + b[i])); console.log(result);
更新:要求解釋。
首先減少將給出的陣列(陣列),並希望減少它下降到單個值(陣列)。 為此,它將調用第一個箭頭函數 2 次。 第一次a將是[2,9,1,2]並且b將是[2,3,9,4] 。 A和B的第一箭函數會返回地圖的。 a是一個數組,它將返回一個數組,其中每個元素都添加到數組b的相應元素中。 第一張地圖的結果將是[4,12,10,6] 。 reduce現在將使用a (第一個映射結果) [4,12,10,6]和b (輸入[4,7,8,1]的最后一個數組元素)第二次調用第一個箭頭函數。 這個箭頭函數會做和之前一樣的事情:返回一個數組,其中每個a元素都被添加到b的相應元素上。 地圖將返回[8,19,18,7] 。 由於沒有更多的輸入元素, reduce將返回該值(數組)。
為了達到預期的結果,使用下面的選項,使用 forEach 的兩個循環
const blockList = [[2, 9, 1, 2], [2, 3, 9, 4], [4, 7, 8, 1]]; const result = []; blockList.forEach((v, index) => v.forEach((val, i) => { result[i] = result[i] ? result[i] : 0; result[i] += val; }) ); console.log(result);
codepen - https://codepen.io/nagasai/pen/yZRrKy?editors=1010
使用嵌套循環:
const blocklist = [[2,9,1,2], [2,3,9,4], [4,7,8,1]], calculatedBlocks = []; for (let j = 0, sum = 0; j < blocklist[0].length; j++, sum = 0) { for (let i = 0; i < blocklist.length; i++) sum += blocklist[i][j]; calculatedBlocks.push(sum); } console.log(calculatedBlocks);
您可以將.reduce
與迭代for...of
循環結合使用,該循環使用 v.entries 提取每個內部數組的索引和值。 然后簡單地通過索引將它們分配給累加器數組並將它們加在一起。
let expectedResult = list.reduce((a,v) => {
for(let [i, n] of v.entries()) a[i] = (a[i] || 0) + n
return a;
}, []);
const list = [ [2, 9, 1, 2], [2, 3, 9, 4], [4, 7, 8, 1] ] let expectedResult = list.reduce((a,v) => { for(let [i, n] of v.entries()) a[i] = (a[i] || 0) + n return a; }, []); console.log(expectedResult);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.