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.

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 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” ]

Do 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.