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.
- 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>
- 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>
- 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
How to remove item from JavaScript array by index
0
In this article, you will learn how to remove an item from a JavaScript array by its inde…
asked
Apu
0 answers
2915
In this article, you will learn how to remove an item from a JavaScript array by its inde…
Answer Link
answered
Apu