I have an array with objects:
[
{
id:1,
parent:null,
value1:22,
value2:33
},
{
id:2,
parent:1,
value1:0,
value2:0
},
{
id:3,
parent:1,
value1:40,
value2:70
},
{
id:4,
parent:2,
value1:40,
value2:70
},
{
id:5,
parent:null,
value1:40,
value2:70
}
]
I want to filter all the elements from array whose parent is present in same array in form of id.
Eg. id 1 and 5 should not present since they have null parent and null id is not there in array.
I tried –
array.filter( (item: IItem)=>{
item.parent == item.id
});
This isnt filtering anything. Getting empty output.
I expect output to be all elements except 1 and 5.
>Solution :
Just to an Array.filter
const data = [
{ id: 1, parent: null, value1: 22, value2: 33 },
{ id: 2, parent: 1, value1: 0, value2: 0 },
{ id: 3, parent: 1, value1: 40, value2: 70 },
{ id: 4, parent: 2, value1: 40, value2: 70 },
{ id: 5, parent: null, value1: 40, value2: 70 },
];
const output = data.filter((node) =>
data.find((item) => node.parent && item.id === node.parent)
);
console.log(output);