I am trying to remove objects from an array of objects using a user specified indexes. When a user specify a range between m
and n
, that's mean that all array having indexes less than m
or higher then n
, I want them to be deleted from the array.
I tried the following when (m=0
and n=7
):
for (const array in this.data) {
if (parseInt(array) <= 0 || parseInt(array) >7) {
this.data.splice(parseInt(array))
}
}
console.log(this.data)
And it's working properly, but once I change m
into 1, all the array is emptied.
Here is a stackblitz.
Your main problem is to get the remaining object after deleting. Here Array.slice function comes for the rescue.
Array.slice does not modify the original array. It just returns a new array of elements which is a subset of the original array.
Array.slice signature
arr.slice(startIndex, endIndex);
Consider the following array:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
To get a slice of an array from values [2, 3, 4, 5], we write:
var slicedArr = arr.slice(2, 6);
Notice that, here, we gave the second argument as 6 and not 5. After executing the above code, we get the values as:
arr // [0, 1, 2, 3, 4, 5, 6, 7, 8]
slicedArr // [2, 3, 4, 5]