Tutorial - JavaScript

How to modify or remove a value from an Array

Removing values from an array is easy and tricky at the same time.

Even creator of Node.js Ryan Dahl got confuse on “How to remove a value from and array” during his Node.js presentation

JavaScript provides three main ways to modify or remove an element from an array :

  • splice()
  • shift()
  • pop()

splice()

splice() method lets you change the content of your array by removing or replacing existing elements with new ones.

Syntax to remove, replace and add a value from array with splice() would look like this

const fruits = ["Banana", "Orange", "Apple", "Mango"];

// Remove element
// At index 2, remove 1 element: 
fruits.splice(2, 1);

console.log(fruits);
// ["Banana", "Orange", "Mango"]


// Replace element
// At index 2, replace 1 element: 
fruits.splice(2, 1, "Lemon");

console.log(fruits);
// ["Banana", "Orange", "Lemon", "Mango"]


// Add element
// At index 2, add 1 element: 
fruits.splice(2, 0, "Lemon");

console.log(fruits);
// ["Banana", "Orange", "Lemon", "Apple" "Mango"]

shift()

shift() method lets you remove the first element of array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];

// Remove first element
fruits.shift();

console.log(fruits);
// ["Orange", "Apple", "Mango"]

pop()

pop() method lets you remove the last element of array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];

// Remove last element
fruits.pop();

console.log(fruits);
// ["Banana", "Orange", "Apple"]

If you enjoyed this post please share, and follow me on DEV.to and Twitter if you would like to know as soon as I publish a post! 🔥