I have a array of object which has sub arrays, I want to delete the subarray object based on the index from both the levels.
For example if want to delete object with id:12 I should pass firstIndex = 0 and secondIndex = 1; Pls note above mentioned eg: is for better understanding of question and not to delete element by id should be deleted based on index only(use case is different and index are received from different source).
const array = [
{
id: 1,
row: [
{id: 11, value: x},
{id: 12, value: y},
{id: 13, value: z},
],
},
{
id: 2,
row: [
{id: 21, value: a},
{id: 22, value: b},
{id: 23, value: c},
],
}
]
firstIndex = 1, secondIndex = 2
const result = [
{
id: 1,
row: [
{id: 11, value: x},
{id: 12, value: y},
{id: 13, value: z},
],
},
{
id: 2,
row: [
{id: 21, value: a},
{id: 22, value: b},
],
}
]
firstIndex = 0, secondIndex = 1
const result = [
{
id: 1,
row: [
{id: 11, value: x},
{id: 13, value: z},
],
},
{
id: 2,
row: [
{id: 21, value: a},
{id: 22, value: b},
{id: 23, value: c},
],
}
]
const result = array.map((el, i) => (i === firstIndex) && el.rows.map(elm, (elm, index) => (index === secondIndex ) && elm.splice(index, 1)))
You can remove Item from array by splice method like this:
const array = [
{
id: 1,
row: [
{id: 11, value: 'x'},
{id: 12, value: 'y'},
{id: 13, value: 'z'},
],
},
{
id: 2,
row: [
{id: 21, value: 'a'},
{id: 22, value: 'b'},
{id: 23, value: 'c'},
],
}
]
firstIndex = 1, secondIndex = 2;
array[firstIndex].row.splice(secondIndex, 1);
console.log(array)
By adding the optional chaining: ? you assure that the code works even if your indexes are wrong, it then just doesn't change anything and you won't get an error
const array = [
{ id: 1, row: [{ id: 11, value: "x" }, { id: 12, value: "y" }, { id: 13, value: "z" }, ], },
{ id: 2, row: [{ id: 21, value: "a" }, { id: 22, value: "b" }, { id: 23, value: "c" }, ], }
]
function deleteByIndex(array, index1, index2) {
array[index1]?.row?.splice(index2, 1)
return array
}
console.log(deleteByIndex(array, 1, 2))