Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu February 14, 2023 › #Array #HowTo

How to remove item from JavaScript array by index

In this article, you will learn how to remove an item from a JavaScript array by its index.

What an index is! #

An index is the numerical position of an element within the array. For example, if you have [4,5], 4 has an index of 0 and 5 has an index of 1 (the first number always starts at 0).

Remove item from JavaScript array by index #

In JavaScript, there are some built-in methods that can be used to delete items based on their positions.

  1. splice() - This method allows us to add or delete one or more elements starting with any given position within the array.
    <script>
     const myArray = ['Red', 'Green' , 'Blue', 'Yellow'];   
           myArray.splice(2,1)
           console.log(myArray) // output - 'Red','Green','Yellow'
    </script>
  2. shift() - This method removes the first element from an array.
    <script>
     const myArray = ['Red', 'Green' , 'Blue', 'Yellow'];
           myArray.shift();
           console.log(myArray) // output - 'Green' , 'Blue', 'Yellow'
    </script>
  3. pop() - Opposite of shift(), this method removes last value of an array.
    <script>
     const myArray = ['Red', 'Green' , 'Blue', 'Yellow'];
           myArray.pop();
           console.log(myArray) // output - 'Red', 'Green' , 'Blue'
    </script>
save
listen
AI Answer
Write Your Answer
loading
back
View All