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

How to filter array based on nested array data?

I have an array with a few objects:

const x = [
  {label: 'a', data: [0,0]},
  {label: 'b', data: [0,0]},
  {label: 'c', data: [0,1]}
  {label: 'd', data: [0,1]},
]

I want to filter out the objects where the data values are equal to 0 and end up with:

const x = [
  {label: 'c', data: [0,1]}
  {label: 'd', data: [0,1]},
]

I 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

const result = x.filter((x) => {
    return x.data.filter((value) => value > 0);
});

expecting the .filter() to only return objects where the value would be higher than 0, but this is not working as expected.

>Solution :

Your inner .filter() method always returns an array, which is considered a truthy value. So the outer .filter() keeps all objects. Instead, you can use .some() to return true if any of the values in the data array are > 0 to keep the object in the resulting array:

const x = [ {label: 'a', data: [0,0]}, {label: 'b', data: [0,0]}, {label: 'c', data: [0,1]}, {label: 'd', data: [0,1]}, ];

const result = x.filter((x) => {
  return x.data.some((value) => value > 0);
});
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