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

Javascript Self – Recursive loop | Find within Filter | Loop Within Same Array

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 –

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

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