0

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.

1
  • Is locationName your array of numbers? If so 1. why type it as any? And 2. Did you think e.g. 1 === [1, 5]?! Commented Jan 17, 2020 at 7:55

2 Answers 2

2

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

Comments

0

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))

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.