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