Skip to content

JavaScript array pop index | Example code

  • by

Use splice() method to pop up element from array at index in JavaScript. You can use random index value of use indexOf method to get the index of any element in Array.

The splice() method can be used to add or remove elements from an array. It takes three arguments:

  • The index where you want to start changing the array
  • The number of elements you want to remove
  • (Optional) The elements you want to add to the array starting at the specified index

JavaScript array pop index

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    const array = [1, 2, 3];

    const index = array.indexOf(2);
    array.splice(index, 1);

    console.log(array)
    
  </script>

</body>
</html> 

Output:

JavaScript array pop index

Only splice if the index exists

<script>
    const array = [2, 5, 9];
    const index = array.indexOf(5);

    if (index > -1) {
      array.splice(index, 1);
    }

    console.log(array); 
    
</script>

Output: [ 2, 9 ]

You can also use the slice() method

 <script>
   const items = ['a', 'b', 'c', 'd', 'e', 'f']
   const i = 3
   const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length))
   console.log(filteredItems)
   
 </script>

Output: [ “a”, “b”, “c”, “e”, “f” ]

Comment if you have any doubts or suggestions on this JS array index topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading