i've got array like this. Unlimited number of nesting possible
const myArray = [
{
id: 1,
children: [
{
id: 3,
children: []
}
]
},
{
id: 2, children: []
}
]
Please, help me to remove any object by id and return new array without it.
The recursiveRemove function will recursively remove the elements from the array and return the new list.
The map function creates copy of the items in the array, you can remove the map if you do not need to retain the original array's sanity.
function recursiveRemove ( list, id ) {
return list.map ( item => { return {...item} }).filter ( item => {
if ( 'children' in item ) {
item.children = recursiveRemove ( item.children, id );
}
return item.id !== id;
});
}
const test1 = recursiveRemove ( myArray, 1);
const test2 = recursiveRemove ( myArray, 2);
const test3 = recursiveRemove ( myArray, 3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With