Home > Software engineering >  Find elements with specific value in a nested array with unknown depth
Find elements with specific value in a nested array with unknown depth

Time:09-03

I have an array with objects for which the nesting depth is unknown and can be different. An example of such an array looks like that:

let exampleArray = [
  {
    id: 'some-id',
    label: "Item 1",
    children: [
      {
        id: 'some-id',
        label: "Child 1",
        children: [
          {
            id: 'some-id', // How to find this for example?
            label: "Child 2",
            children: []
          }
        ]
      }
    ]
  },
  {
    id: 'some-id',
    label: "Item 2",
    children: [
      {
        id: 'some-id',
        label: "Child 1",
        children: [
          {
            id: 'some-id',
            label: "Child 2",
            children: []
          }
        ]
      }
    ]
  }
]

Each array item can have a nested array children. The basic structure is the same as the parent one.

The challenge

When I for example want to delete a nested element with a specific id, how could I do this? I think it would not be the best practice to start iterations with a static number of loops, because I don't know how big the array is nested.

If I know the ID from the children element, can I say something like: "Iterate the entire array including all nesting and find the element with the ID xy?".

Or what would be the best practice to handle such nested arrays?

CodePudding user response:

A recursive function is likely what you're looking for:

function deleteById(data, id){
    for(var x = 0; x < data.length; x  ){
        if(data[x].id === id){
            data.splice(x, 1); // if it matches, remove it from the array
        }
        else{
            deleteById(data[x].children, id);
        }
    }
}
  • Related