[英]How to use the sum of values in an array inside FOR loop Node Js
我的問題是我想獲得具有 RATIO 的 SplitType 的 SplitValue 的總和,並在 FOR 循環中使用它來計算拆分的比率。 即 3 + 2 = 5。我在下面每一行代碼中所做的評論解釋了我的麻煩,我得到了 3 和 5 的循環,而不是只有 5。謝謝
var details = { "Amount": 1396.8000000000002, "SplitInfo": [{ "SplitType": "RATIO", "SplitValue": 3 }, { "SplitType": "RATIO", "SplitValue": 2 } ] }; var conRatioSumArr = 0; var balance = details.Amount; for (var i = 0; i < details.SplitInfo.length; i++) { // I want to Get the total sum of SplitValue that has the SplitType of RATIO // 3 + 2 = 5 // Here is what I've tried splitTypeArr = details.SplitInfo[i].SplitType; splitValueArr = details.SplitInfo[i].SplitValue; if (splitTypeArr === "RATIO") { conRatioSumArr += splitValueArr; console.log(conRatioSumArr); // This gives me a loop of 3 & 5. I only need the total value which is 5 instead of both 3 and 5. Note that if I put this outside the for loop, I get only the total which is 5, but I want to use the sum inside of this for loop not outside the for loop to enable me calculate the ratio below. splitAmount = (balance * (splitValueArr / 5)); // The total above is expected to replace the 5 here, but I'm getting a loop of 3 & 5 instead. // Like this // splitAmount = (balance * (splitValueArr / conRatioSumArr)); // splitAmount is expected to give: 838.08 and 558.7200000000001 split respectively console.log(splitAmount); } }
這段代碼很容易理解和修改我希望你喜歡。 使用數組方法reduce
。
var details = { "Amount": 1396.8000000000002, "SplitInfo": [{ "SplitType": "RATIO", "SplitValue": 3 }, { "SplitType": "RATIO", "SplitValue": 2 } ] }; var result = details.SplitInfo.reduce(function(agg, item) { if (item.SplitType == "RATIO") { agg.sum = (agg.sum || 0) + item.SplitValue agg.count = (agg.count || 0) + 1 } return agg; }, {}) console.log(result) console.log("average is " + result.sum / result.count)
我認為你把它弄得太復雜了。
您需要做的就是獲得比例中的零件總數,然后進行(簡單)數學運算。
var details = {
amount: 1396.8000000000002,
splitInfo: [
{
type: "RATIO",
value: 3,
},
{
type: "RATIO",
value: 2,
},
],
};
let totalParts = 0;
for (const split of details.splitInfo) {
if (split.type == "RATIO") totalParts += split.value;
}
for (const split of details.splitInfo) {
if (split.type == "RATIO") {
let amountForSplit = details.amount * (split.value / totalParts);
console.log(amountForSplit);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.