I have an array of nested objects. These objects take one of two forms:
// type a
{
value: 'some value'
}
or
// type b
{
array: [
object of type a or b,
object of type a or b,
...
]
}
So, the base array can be nested infinitely. Given a series of indices (I've been calling it a 'tree'), how can I remove a single item at any depth?
A sample of what I have so far:
const baseArray = [
{ value: 'some value' },
{ array: [
{ value: 'some value' },
{ array: [
{ value: 'some value' },
{ value: 'some value' },
],
},
{ value: 'some value' },
{ array: [
{ value: 'some value' },
{ array: [
{ value: 'delete me' },
{ value: 'some value' },
]
},
],
},
],
}
]
const tree = [1, 3, 1, 0]
function deleteNested(tree, inputArray) {
const index = tree.shift();
console.log(inputArray, index);
const child = inputArray[index].array;
if (tree.length > 0) {
console.log(child)
return deleteNested(tree, child);
}
return [
...inputArray.slice(0, index),
...inputArray.slice(index + 1)
]
}
const originalArray = baseArray.slice(0);
console.log(deleteNested(tree, baseArray), originalArray);
I want to delete the marked object given it's 'tree' location: [1, 3, 1, 0]:
- first, look in the 1 (index of 1, not 0) value of the initial array,
- then the 3 value,
- then look at the 1 value,
- then finally remove the 0 value.
What I have above isn't working, but has gotten me started.
The function needs to be recursive to work at any depth. It should ideally not use splice() to avoid modifying the array passed into it -- rather, it should return a new one.