var arr = [1,2,3,5,6];
I want to remove the first element of the array so that it becomes:
var arr = [2,3,5,6];
To extend this question, what if I want to remove the second element of the array so that it becomes:
var arr = [1,3,5,6];
Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
Answer: Use the splice() Method You can use the splice() method to remove the item from an array at specific index in JavaScript. The syntax for removing array elements can be given with splice(startIndex, deleteCount) .
shift()
is ideal for your situation. shift()
removes the first element from an array and returns that element. This method changes the length of the array.
array = [1, 2, 3, 4, 5]; array.shift(); // 1 array // [2, 3, 4, 5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With