Home > Web Front-end > JS Tutorial > How Can I Remove a Specific Item from an Array in JavaScript?

How Can I Remove a Specific Item from an Array in JavaScript?

Barbara Streisand
Release: 2024-12-28 17:51:16
Original
137 people have browsed it

How Can I Remove a Specific Item from an Array in JavaScript?

Removing Specific Array Items in Core JavaScript

Want to remove a particular value from an array effortlessly? Core JavaScript offers a straightforward approach.

Approach:

  1. Utilize indexOf to determine the index of the element you wish to remove.
  2. Employ the splice method to eliminate the element at that index.

splice() Method:

The splice() method allows you to modify an array by removing existing elements or inserting new ones.

Example:

Consider the array [2, 5, 9]. To remove the value 5, follow these steps:

const array = [2, 5, 9];

const index = array.indexOf(5); // Find the index of the element
if (index > -1) { // Only splice array if item is found
  array.splice(index, 1); // 2nd parameter removes only one item
}

// array = [2, 9]
Copy after login

In this example, the indexOf method finds the index of the value 5, which is 1. The splice method then removes the element at index 1, yielding the modified array [2, 9].

The above is the detailed content of How Can I Remove a Specific Item from an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template