![](/img/trans.png)
[英]How to find the sum of values that are inside a nested array using mongodb aggregation?
[英]Find the sum of values inside a nested array
我有一個看起來像這樣的嵌套數組:
let scores = [
[[2, 1, 0], [2, 1, 0]],
[[4, 2, 0]],
[[4, 2, 0]],
[[4, 2, 0],[2, 1, 0]]
]
我想做的是獲取每個數組的最大值(並對包含多個數組的數組中的最大值求和,即在第一個數組[[2,1,0],[2,1 ,0]],我需要將每個數組的最高值相加,在這種情況下為2 + 2。)我的想法是將shift()每個數組的第一個值或slice()/刪除較低的值,所以我的數組看起來像這樣:
newScores = [[[2],[2]], [4], [4], [[4],[2]]]
最終,我想要的輸出是: output = [[4], [4], [4], [6]]
希望有人能提供一些指導! 謝謝!
您需要迭代父數組,然后對其中的每個數組進行迭代-遍歷其數組,從每個數組中獲取最大數量-然后對子數組求和,最后將總數推入輸出數組。
let scores = [ [[2, 1, 0], [2, 1, 0]], [[4, 2, 0]], [[4, 2, 0]], [[4, 2, 0],[2, 1, 0]] ] var output = []; scores.forEach(function(score) { var total = 0 score.forEach(function(arr) { total += arr.reduce(function(a, b) { return Math.max(a, b); }); }) output.push(total); }) console.log(output); // gives [4,4,4,6]
const result = scores.map(groups =>
groups.map((sum, group) => sum + Math.max(...group), 0)
);
您可以使用map()
, reduce()
和Math.max
方法以及傳播語法...
來做到這一點。
let scores = [ [[2, 1, 0], [2, 1, 0]], [[4, 2, 0]], [[4, 2, 0]], [[4, 2, 0],[2, 1, 0]] ] const result = scores.map(a => a.reduce((r, e) => { return +r + Math.max(...e) }, [])) console.log(result)
let scores = [
[[2, 1, 0], [2, 1, 0]],
[[4, 2, 0]],
[[4, 2, 0]],
[[4, 2, 0],[2, 1, 0]]
]
function nestedArray(arr){
let result=[];
let counter = 0;
for(let i=0;i<arr.length;i++){
if(arr[i].length>1){
var a = [Math.max(...arr[i][counter])];
var b = [Math.max(...arr[i][counter+1])];
result.push(a.map((ax,bx)=>ax+b[bx]));
}
if(arr[i].length===1){
result.push([Math.max(...arr[i][counter])]);
}
}
return result;
}
nestedArray(scores);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.