Light ModeDark ModeReset dark mode. Falls back to OS dark mode setting.


No results for 'undefined'

Blog Posts

No results for 'undefined'
Powered by Algolia

JavaScript, Find Specific Element in Array and Delete It, Using the Splice() Method

Sep 29, 20171 min readJavaScriptViews:

Computers start counting from zero. So 0 is 1, 1 is 2, and so on. That’s why list[2] selects item 3 from the array

Code for the array in the example:

var list = ['item 1', 'item 2', 'item 3', 'item 4']

splice() needs two things to work:

  • A number to specifiy which position you want to delete from.
  • A number to specify how many items we want to delete, from that position.

So list.splice(2, 1) targets the 3th item in the array, and deletes that single item.

If you instead wrote: list.splice(2, 2) then it would delete both the 3th and the 4th item in the array.

The second number in splice() specifies how many elements we want to delete, from the position we target. If we had 10 items in an array and wrote list.splice(3, 5) then it would delete 5 items from the 4th position in the array.