0

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)
      }
3
  • 2
    That does not look related to rxjs nor angular in any way, it's not well formatted, you say what you want but not what's the issue. If you want people to spend time helping you out, try to help people by using the right tags, formatting your code, and explaining appropriately Commented Jul 12, 2023 at 16:05
  • It looks like the first set of code is getting the product id and corresponding amount as you said you wanted. Are you trying to use Reduce to total the amounts? If so, wouldn't the result be a scalar number, not an array? Commented Jul 12, 2023 at 16:32
  • What does the code shown have to do with the question title? You appear to want to group the newArray by article_id and sum the data. We have many questions about this process, (e.g., this question). Note that these usually initialize the value to 0 rather than ''... Commented Jul 12, 2023 at 16:42

1 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.