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 (blade) view file exists

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to hide directory listing in .htaccess?

What is the max size, by default, of GET variables?

How to hide certain file types from directory listings

How to create random numbers in JS?

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

How to block an IP address in .htaccess

What are PHP's PSRs?

How to find the intersection (same values) from two arrays?