英文:
array reduce return concat number
问题
我想使用Reduce()方法来获取产品ID和相应的金额。
apiArray可能是从ApiRest获取的数组
const newArray = apiArray.map((items) => {
return {
article_id: items.article_id,
montant : items.montant
}
})
const finalArray = newArray.reduce((acc, curr)=>{
if (!acc[curr.article_id]) {
acc[curr.article_id] = '';
}
acc[curr.article_id] += -(-curr.montant) ;
return acc;
},{});
console.log('finalArray==',finalArray)
}
英文:
I wanted to use Reduce() method to get the product id and the corresponding amount
apiArray is may array get from ApiRest
const newArray = apiArray.map((items) => {
return {
article_id: items.article_id,
montant : items.montant
}
})
const finalArray = newArray.reduce((acc:any, curr)=>{
if (!acc[curr.article_id]) {
acc[curr.article_id] = '';
}
acc[curr.article_id] += -(-curr.montant) ;
return acc;
},{});
console.log('finalArray==',finalArray)
}
</details>
# 答案1
**得分**: 0
尝试使用map()和reduce()函数:
```javascript
const apiArray = [
{ article_id: 1, montant: 10 },
{ article_id: 2, montant: 5 },
{ article_id: 1, montant: 7 },
{ article_id: 3, montant: 3 },
{ article_id: 2, montant: 2 }
];
const newArray = apiArray.map(items => ({
article_id: items.article_id,
montant: items.montant
}));
const finalArray = newArray.reduce((acc, curr) => {
if (!acc[curr.article_id]) {
acc[curr.article_id] = 0;
}
acc[curr.article_id] += curr.montant;
return acc;
}, {});
console.log('finalArray:', finalArray);
英文:
Try using map() and reduce() function:
const apiArray = [
{ article_id: 1, montant: 10 },
{ article_id: 2, montant: 5 },
{ article_id: 1, montant: 7 },
{ article_id: 3, montant: 3 },
{ article_id: 2, montant: 2 }
];
const newArray = apiArray.map(items => ({
article_id: items.article_id,
montant: items.montant
}));
const finalArray = newArray.reduce((acc, curr) => {
if (!acc[curr.article_id]) {
acc[curr.article_id] = 0;
}
acc[curr.article_id] += curr.montant;
return acc;
}, {});
console.log('finalArray:', finalArray);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论