0

Trying to understand Array.splice().

deleteCount: An integer indicating the number of old array elements to remove.

Ok. Seems straightforward. I want to remove the last 4 objects in the array. I hope that's the same as elements?

arr.splice(<start>, deleteCount<how-many-to-remove>):


// {0 - 8} is an example of object position
let obArr = [{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}]

// Start from the last and remove four:
obArr.splice(-1, 4)

console.log(obArr) // not expected.

console.log(obArr) // expected: [{0}, {1}, {2}, {3}]
6
  • Don't use splice at all, it is considered a bad practice. Instead use array.slice and it's not python so -1 won't work in slice as well. Commented Dec 10, 2018 at 16:30
  • Would you care to add another way instead of splice? Commented Dec 10, 2018 at 16:31
  • @Zydnar why do say -1 won't work in slice? Commented Dec 10, 2018 at 16:33
  • I assumed -1 means the "last" as indexOf? Commented Dec 10, 2018 at 16:35
  • @MarkMeyer it's not what I mean, it will simply work the same way, but it won't change obArr so it's not what OP wants. Commented Dec 10, 2018 at 16:36

1 Answer 1

5

Your code starts at the last item and tries to remove four values after the last item. But there aren't four values after the last item. If you want to remove four from the end start earlier in the array:

let obArr = [0, 1, 2, 3, 4, 5, 6, 7]

// Start from the 4th last and remove four:
obArr.splice(-4, 4)

console.log(obArr) 

Sign up to request clarification or add additional context in comments.

1 Comment

Readability is now understandable "Start from the 4th last and remove four". Many thanks

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.