英文:
Sum values in array
问题
以下是代码部分的翻译:
const App = (props) => {
let array = [
{
amount: "12",
amount2: "0",
type: "Purchased"
},
{
amount: "0",
amount2: "34",
type: "Donation"
}
];
const total = (data) => {
let tempSub = [];
let sum;
if (data.length > 0) {
data.map((i, k) => {
let productTotal = i.amount;
let donationTotal = i.amount2;
tempSub.push(i.type === "Purchased" ? productTotal : donationTotal);
});
sum = tempSub.reduce(function (a, b) {
return a + b;
}, 0);
} else {
sum = 0;
}
return sum;
};
return (
<>
{array.length > 0
? array.map((item, i) => {
return <>{total(item)}</>;
})
: ""}
</>
);
};
export default App;
请注意,这是代码的翻译,只包括代码本身,没有其他内容。
英文:
I am trying to get the values in the array
based on their type
and then sum everything at total(item)
. The result returns concatenated values instead of a sum.
const App = (props) => {
let array = [
{
amount: "12",
amount2: "0",
type: "Purchased"
},
{
amount: "0",
amount2: "34",
type: "Donation"
}
];
const total = (data) => {
let tempSub = [];
let sum;
if (data.length > 0) {
data.map((i, k) => {
let productTotal = i.amount;
let donationTotal = i.amount2;
tempSub.push(i.type === "Purchased" ? productTotal : donationTotal);
});
sum = tempSub.reduce(function (a, b) {
return a + b;
}, 0);
} else {
sum = 0;
}
return sum;
};
return (
<>
{array.length > 0
? array.map((item, i) => {
return <>{total(item)}</>;
})
: ""}
</>
);
};
export default App;
答案1
得分: 1
返回在reduce回调函数中的parseInt(a) + parseInt(b)。
英文:
Please return parseInt(a) + parseInt(b) in reduce callback function
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论