Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove element from an array in JavaScript?

var arr = [1,2,3,5,6]; 

Remove the first element

I want to remove the first element of the array so that it becomes:

var arr = [2,3,5,6]; 

Remove the second element

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]; 
like image 221
user198729 Avatar asked Jan 05 '10 02:01

user198729


People also ask

How do you remove an element in JavaScript?

Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

What does remove () do JS?

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.

How do you remove an element from an array at a specific index JavaScript?

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) .


1 Answers

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] 
like image 99
JP Silvashy Avatar answered Oct 08 '22 15:10

JP Silvashy