Home > front end >  I need to map an array object and then filter it
I need to map an array object and then filter it

Time:07-02

I have this array of objects

const mainCurrencies: string[] = ['GBP','EUR']
const accounts: AccountDetail[] = [{currency:'GBP',date:'20/06/2022'}{currency:'EUR',date:'20/06/2022'},{currency:'CAD',date:'20/06/2022'},{currency:'ZAR',date:'20/06/2022'}]

I want the currencies that are not main currencies to change from their names to 'OTHER' e.g {currency:'ZAR',date:'20/06/2022'} -> {currency:'OTHER',date:'20/06/2022'}

Then remove the duplicate OTHER objects My Code is below

accounts.map(account => {
 if (!mainCurrencies.includes(account.currency)) {
  account.currency = 'OTHER'
 }
}).filter((account) => {
  account.currency != 'OTHER'
})

CodePudding user response:

const mainCurrencies = ['GBP','EUR'];

const accounts = [{currency:'GBP',date:'20/06/2022'},{currency:'EUR',date:'20/06/2022'},{currency:'CAD',date:'20/06/2022'},{currency:'ZAR',date:'20/06/2022'}];

const mappedAndFilteredAccounts = accounts.map(account => ({
  ...account,
  currency: mainCurrencies.includes(account.currency) ? account.currency: 'OTHER',
})).filter(
  (item, index, arr) => arr.findIndex(
   e => e.currency === item.currency && e.date === item.date,
  ) === index,
);

console.log(mappedAndFilteredAccounts);

CodePudding user response:

 const result = accounts
      .reduce(
        (previous, account) =>
          mainCurrencies.includes(account.currency) ? previous.concat(account) : previous.concat({ currency: 'OTHER', date: account.date }),
        [] as AccountDetail[]
      )
      .filter((item, index, arr) => arr.findIndex((e) => e.currency === item.currency && e.date === item.date) === index);

Please note that this solution will remove all duplicates, not only the ones with currency OTHER.

CodePudding user response:

Here is a version using reduce:

const adjustedAccounts = accounts.reduce((p: AccountDetail[], c: AccountDetail) => {
    if (!mainCurrencies.includes(c.currency)) {
        if (p.some(a => a.currency === 'OTHER' && a.date === c.date))
            return p;
        else
            c.currency = 'OTHER';
    }
    return [...p, c];
}, []);

Note that this solution mutates the original AccountDetail objects.

  • Related