Search code examples
javascriptarraysobjectrecursionreduce

Recursive function to filter out array of objects based on ID regardless of parent or children elements


I need to filter the below array of objects based on ID regardless of parent or child, if _id is found in the parent then remove that element and return rest, and if it is found in a child, then remove that child element and return rest.

const arrayToBeFiltered = [
  {
    _id: "1",
    assets: [
      {
        _id: "2",
      },
      {
        _id: "3",
      },
    ],
  },
  {
    _id: "4",
    assets: [
      {
        _id: "5",
      },
    ],
  },
];

So, if I pass 3 then it should return:

[
  {
    _id: "1",
    assets: [
      {
        _id: "2",
      },
    ],
  },
  {
    _id: "4",
    assets: [
      {
        _id: "5",
      },
    ],
  },
];

And if I pass 4 then it should return:

[
  {
    _id: "1",
    assets: [
      {
        _id: "2",
      },
      {
        _id: "3",
      },
    ],
  },
];

Solution

  • Try the below code for reference :

    const arrayToBeFiltered = [
      {
        _id: "1",
        assets: [
          {
            _id: "2",
          },
          {
            _id: "3",
          },
        ],
      },
      {
        _id: "4",
        assets: [
          {
            _id: "5",
          },
        ],
      },
    ];
    
    function removeIdFromArray(array, idToRemove) {
      return array.filter((element) => {
        if (element._id === idToRemove) {
          return false;
        }
    
        if (element.assets) {
          element.assets = removeIdFromArray(element.assets, idToRemove);
        }
    
        return true;
      });
    }
    
    
    
    const newArray = removeIdFromArray(arrayToBeFiltered, "3");
    console.log(JSON.stringify(newArray));