1

I have an array of bank accounts, which I receive from a GET request.

<div class="card" *ngFor="let acc of accounts">{{acc.iban}}  ({{acc.currency}})>

Accounts array is for example like that:

this.accounts = [
    { iban : '123' , currency: 'EUR' },
    { iban:  '123' , currency: 'USD' },
    { iban:  '234' , currency: 'EUR' }
]

How can I dynamically find accounts with the same iban, remove one of them from the list, and add removed the account's currency to the other account ?

The expected output is:

this.accounts = [
    { iban: '123' , currency 'EUR, USD' },
    { iban:  '234' , currency: 'EUR' }
]

1 Answer 1

1

You can use Object.values() and Array.prototype.reduce() to merge the accounts with the same IBAN and join the currencies with a comma.

With reduce, you iterate on your accounts array and build an intermediate dictionary that maps the iban to the merged accounts, then with Object.values() you enumerate the values of the dictionary entries to return an array.

const accounts = [
  { iban : '123' , currency: 'EUR' },
  { iban:  '123' , currency: 'USD' },
  { iban:  '234' , currency: 'EUR' }
];

const result = Object.values(accounts.reduce((acc, { iban, currency }) => {
  acc[iban] = acc[iban]
    ? { ...acc[iban], currency: acc[iban].currency + ', ' + currency }
    : { iban, currency };
  return acc;
}, {}));

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! :)

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.