I have an array formed as follows:
descriptionAndItem = [
{
description: 'Transaction A',
items: [
{ status: 1, description: 'Item A', code: 4 },
{ status: 1, description: 'Item B', code: 3 },
],
},
{
description: 'Transaction B',
items: [{ status: 0, description: 'Item C', code: 8 }],
},
{
description: 'Transaction C',
items: [
{ status: 1, description: 'Item D', code: 4 },
{ status: 0, description: 'Item E', code: 8 },
],
},
];
From that information I must filter only those that have the status of the item equal to one, for this I use the function filter
and find
in the following way:
let filterData = this.descriptionAndItem.filter((x: any) =>
x.items.find((y: any) => y.status === 1)
);
But when there is more than one item and only one of them has the status equal to one, the filter also shows the item that has the status equal to zero. How could I do the filtering so that it does not show that item or eliminates it.
Demo: Stackblitz
You could iterate through your parent array using reduce , and within it use
filter
to get the elements that meet the conditions.The key is inside the
if
, in which we create a constant that will have the element that is going through, and to that element we attach only the corresponding items .You tell us how it goes.
The best way in my opinion is using
.reduce
, but following the logic you used, you should use another.filter
inside.filter
(instead of.find
). Because there are two things you want to filter, "transactions" and "items". What happens is that.filter
it does not alter each element, it is onlytrue
orfalse
, it is complete or it is not. But this does not prevent us from manually altering it before telling it that this or that element will be "allowed" (true
). Then you could do:Where the third parameter of the first
.filter
is the original array, it is the same as if we useddescriptionAndItem
.In this way, in each iteration of the first
.filter
we alter the original array (represented witho
) before deciding whether it will be there or not, said alteration is another.filter
. After the alteration, if it turns out toitems
have zero elements, the parent of will not be includeditems
in the final array.