Remove an item from an array with a specific value in JavaScript

Remove an item from an array with a specific value in JavaScript

While working on any project, you often get an array that you need to filter out an item before moving on. In this W3 Schools Vanilla JavaScript Tutorial, we will learn how to remove an item from an array by a specific value.

Suppose you have an array named cities. Let's create it first for demonstration.

let cities = ['Washington', 'Seattle', 'Mumbai', 'Karachi', 'Dhaka'];

console.log(cities); // Check the result

Goal: You have an array named cities containing ['Washington', 'Seattle', 'Mumbai', 'Karachi', 'Dhaka'] and you want to remove an item from it that has the value of 'Seattle'.

There are various ways to achieve this goal. Choose the one that is appropriate for you.

Method 1: Remove item using EcmaScript 6 (ES6) filter() method

let city_to_remove = 'Seattle';

cities = cities.filter(item => item !== city_to_remove );

console.log(cities); // Check the result

Result: The result would be without 'Seattle' ['Washington', 'Mumbai', 'Karachi', 'Dhaka']

Method 2: Remove the item using the older way with the splice() method

let index_of_city = cities.indexOf('Seattle'); // get the key/index of array item with the value of 'Seattle'

if (index_of_city > -1) { // Check if the constant has an valid index key defined
  cities.splice(index_of_city , 1); // Removes an array item with that index
}

console.log(cities ); // Check the result

Result: The result would be without 'Seattle' ['Washington', 'Mumbai', 'Karachi', 'Dhaka']

Leave a Reply

Your email address will not be published. Required fields are marked *