How to add and remove items to an array in JS?

JavaScript: How to add and remove items to an array in JS?

If you want to add items to an array in javascript, you can use the push() method to add it to the end of an array.

  1. let fruits = ["apple","banana","orange","grapes"];
  2. fruits.push("kiwi"); //kiwi will be the last item (after grapes) in the array

Or to add it to the start of an array, use unshift.

  1. let fruits_2 = ["apple","banana","orange","grapes"];
  2. fruits_2.unshift("kiwi"); // kiwi will be the first item in the array (before apple)

How to remove items from JS arrays?

You can use .pop() and .unshift().

Using pop() to remove items from Javascript arrays

To remove an item from the end of an array, you use .pop():

  1. let fruits_3 = ["apple","banana","orange","grapes"];
  2.  
  3. fruits_3.pop();
  4. console.log(fruits_3) // (3) ["apple", "banana", "orange"]

Using unshift() to remove items from a JS array

To remove an item from the start of an array, you use .unshift():

  1. let fruits_4 = ["apple","banana","orange","grapes"];
  2.  
  3. fruits_4.shift();
  4. console.log(fruits_4) // (3) ["banana", "orange", "grapes"]
webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to add and remove items to an array in JS?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the JavaScript language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to check if a relation was loaded on an Eloquent model already?

How to block access to certain referrers in Apache using .htaccess

How to add a name prefix to all routes in a group?

What are macros in Laravel?

How to show a specific view file for certain error codes?

How to query mysql using PDO in PHP?

How to block multiple IP addresses in .htaccess

How to split a string into an array, in JS

How to eager load multiple levels of relationships in Eloquent?

What are route patterns in Laravel?