Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter a object based on another Array

I am trying to filter a object based on an another array.

data = {
  'TypeA': ['A1', 'A2', 'A3', 'A4'],
  'TypeB': ['B1', 'B2', 'B3', 'B4'],
  'TypeC': ['C1', 'C2', 'C3', 'C4'],
}

array = ['TypeA', 'TypeB']

I want to get a new array with the values of both ‘TypeA’ and ‘TypeB’ like [‘A1’, ‘A2’, ‘A3’, ‘A4’, ‘B1’, ‘B2’, ‘B3’, ‘B4’] and remove duplicates if any also.

so far i have tried,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

tTmp_Arr = data.filter(tObj => array.includes(tObj))

Any help is much appreciated.

Thanks in advance.

Thanks,

>Solution :

You can’t use filter on objects. You can get the result by flatmapping and then filtering as:

const data = {
  'TypeA': ['A1', 'A2', 'A3', 'A4'],
  'TypeB': ['B1', 'B2', 'B3', 'B4'],
  'TypeC': ['C1', 'C2', 'C3', 'C4'],
};

const array = ['TypeA', 'TypeB'];

const result = array
  .flatMap(key => data[key] || []) 
  .filter((item, index, self) => self.indexOf(item) === index);
  
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading