pmiranda
pmiranda

Reputation: 8450

How to filter data by matching currency code

I have this array:

[
  {
    code: 'A',
    currencies: [ 'USD' ],
  },
  {
    code: 'B',
    currencies: [ 'USD', 'PEN' ],
  }
]

I need to remove from currencies the value USD only when code = B

So the output should be:

[
  {
    code: 'A',
    currencies: [ 'USD' ],
  },
  {
    code: 'B',
    currencies: [ 'PEN' ],
  }
]

I'm trying this but I'm gettin an empty array.

https://jsfiddle.net/5sroy47a/

const items = [{
    code: 'A',
    currencies: ['USD'],
  },
  {
    code: 'B',
    currencies: ['USD', 'PEN'],
  }
];

const itemFiltered = items.filter(item => {
  console.log('item', item);
  if (item.code === 'B') {
    let currencies = item.currencies;
    currencies = currencies.filter(currency => currency !== 'USD')
  }
});

console.log('itemFiltered: ', itemFiltered);

Upvotes: 1

Views: 254

Answers (3)

Hasan URAL
Hasan URAL

Reputation: 31

The filter function adds a boolean filter. It does not return the curencies array, unfortunately. You can use the Map function to reach the lower arra. Since the map function returns you as an array, you have to convert it to a singular arra with Reduce. Afterwards, you can reach the result by applying your filter again.

const filtered=items.filter(item => item.code === 'B').map(m=>m.currencies).reduce(function(a, b){ return a.concat(b); }).filter(f=>f !== 'USD');

https://jsfiddle.net/metalsimyaci/ga94ukb7/

Upvotes: 1

uingtea
uingtea

Reputation: 6534

for dynamic data you can try this

const items = [{
    code: 'A',
    currencies: ['USD'],
  },
  {
    code: 'B',
    currencies: ['USD', 'PEN', 'KRW'],
  },
  {
    code: 'C',
    currencies: ['KRW', 'IDR', 'USD', 'PEN'],
  }
];

currenctFiltered = []
const itemFiltered = items.map(item => {
  item.currencies = item.currencies.filter(currency => {
    if (!currenctFiltered.includes(currency)) {
      currenctFiltered.push(currency)
      return currency;
    }
  })
  return item
});

console.log('itemFiltered: ', itemFiltered);

Upvotes: 1

wangdev87
wangdev87

Reputation: 8751

You can just use Array.map().

const items = [{
    code: 'A',
    currencies: ['USD'],
  },
  {
    code: 'B',
    currencies: ['USD', 'PEN'],
  }
];

const itemFiltered = items.map(item => {
  if (item.code === 'B') {
    item.currencies = item.currencies.filter(currency => currency !== 'USD')
  }
  return item
});

console.log('itemFiltered: ', itemFiltered);

Upvotes: 4

Related Questions