Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Filtering array of objects based on array

I am trying to filter one array of objects that looks like this

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' }
];

And an array that looks like this

const values = [1,5];

What I need is to filter ELEMENT_DATA to NEW_VALUES look like this

const NEW_VALUES: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' }
];

I have tried with filter like this:

  filterData(locationName: any) {
    return ELEMENT_DATA.filter(object => {
      return object.position === locationName;
    });
  }

but always I get an empty array.

Upvotes: 0

Views: 48

Answers (2)

Sohan
Sohan

Reputation: 6809

You can use Array.prototype.filter()

ELEMENT_DATA.filter(function (object) {
  return locationName.indexOf(object.position) !== -1; // -1 means not present
});

or with underscore JS , using the same predicate:

_.filter(ELEMENT_DATA, function (object) {
  return locationName.indexOf(object.position) !== -1; // -1 means not present
}

If you have access to ES6 collections or a polyfill for Set. Here locationName should be a type of Set

ELEMENT_DATA.filter(object=> locationName.has(object.position))

Upvotes: 0

iY1NQ
iY1NQ

Reputation: 2514

If the locationName gets as input [1,5] then the code should look like this:

 filterData(locationName: number[]) {
    return ELEMENT_DATA.filter(object => {
      return locationName.includes(object.position);
    });
  }

Upvotes: 2

Related Questions