1

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.

1
  • 2
    It would be easier if you think about the problem as - what items should remain after the removal? Create a new list of the items that remain const x = data.slice(m, n) then assign this.data = x. Commented Jun 23, 2020 at 7:00

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

Comments

2

The second argument to Array.splice is the number of elements to remove. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_splice

If not specified it will remove all the elements from the specified index including specified index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.