MOCKSTACKS
EN
Questions And Answers

More Tutorials









Javascript Removing items from an array

Shift

Use .shift to remove the first item of an array.


var array = [1, 2, 3, 4];
array.shift();

Output

[2, 3, 4]

Pop

Further .pop is used to remove the last item from an array.
For example:


var array = [1, 2, 3];
array.pop();

Output

[1, 2]

Splice

Use .splice() to remove a series of elements from an array. .splice() accepts two parameters, the starting index, and an optional number of elements to delete. If the second parameter is left out .splice() will remove all elements from the starting index through the end of the array.


var array = [1, 2, 3, 4];
array.splice(1, 2);

Output

[1, 4]

The return of array.splice() is a new array containing the removed elements. For the example above, the return would be:

Output

[2, 3]

Delete

Use delete to remove item from array without changing the length of array:


var array = [1, 2, 3, 4, 5];
console.log(array.length); // 5
delete array[2];
console.log(array); // [1, 2, undefined, 4, 5]
console.log(array.length); // 5

Array.prototype.length

Assigning value to length of array changes the length to given value. If new value is less than array length items will be removed from the end of value.


array = [1, 2, 3, 4, 5];
array.length = 2;
console.log(array);

Output

[1, 2]


Conclusion

In this page (written and validated by ) you learned about Javascript Removing items from an array . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Removing all elements.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.