skip to Main Content

I have the following filters array which contains the following three values:

['serviceCode1', 'serviceCode2', 'serviceCode3']

I have an another array which contains roughly 78 records, I’m trying to filter this based on the filters listed above.

  this.mainDataSet = this.mainDataSet.filter((data) => {
    return this.filters.forEach(x => data.serviceCode.includes(x.code!))
   });

Yet the response is always 0, even when the mainDataSet includes values listed inside the filters array, can someone shed some light in what I’m doing wrong here?

2

Answers


  1. Array.forEach() is used to iterate elements, but it won’t return any value.

    You should work with Array.find() in order to filter element in the array based on another array.

    this.mainDataSet = this.mainDataSet.filter((data) => 
      this.filters.find(x => data.serviceCode.includes(x)));
    
    Login or Signup to reply.
  2. forEach does not return a value, it operates on the array in place, so you are just doing work on the filters array not on the dataset since nothing is returning from your inner function.

    I would use the includes method to match the dataset to the filters list. It’s much more readable.

    const filters = [
      'serviceCode1', 
      'serviceCode2', 
      'serviceCode3'
    ]
    
    const filteredDataSet = 
      mainDataSet.filter((data) => filters.includes(data.serviceCode));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search