数组减少返回连接数字

huangapple go评论69阅读模式
英文:

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 =&gt; ({
  article_id: items.article_id,
  montant: items.montant
}));

const finalArray = newArray.reduce((acc, curr) =&gt; {
  if (!acc[curr.article_id]) {
    acc[curr.article_id] = 0;
  }
  acc[curr.article_id] += curr.montant;
  return acc;
}, {});

console.log(&#39;finalArray:&#39;, finalArray);

huangapple
  • 本文由 发表于 2023年7月13日 00:00:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定