Home >Web Front-end >JS Tutorial >How Can I Remove a Specific Element from a JavaScript Array Using Only Core JavaScript?

How Can I Remove a Specific Element from a JavaScript Array Using Only Core JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 05:53:14392browse

How Can I Remove a Specific Element from a JavaScript Array Using Only Core JavaScript?

Core JavaScript: Removing Specific Items from Arrays

Question: Can I remove a particular element from an array? I would like to use a method similar to array.remove(value).

Note: Core JavaScript is required; frameworks are not permitted.

Answer:

To remove a specific value from an array in JavaScript, you can use the following steps:

  1. Utilize the indexOf method to retrieve the index of the element you wish to remove.
  2. Employ the splice method to eliminate the identified index.

Explanation of splice:

The splice method modifies an array by:

  • Deleting existing elements
  • Adding new elements

Example Code:

const array = [2, 5, 9];

console.log(array);

// Search for specific element
const index = array.indexOf(5);

// Remove element if found
if (index > -1) { // only splice array when item is found
  array.splice(index, 1); // 2nd parameter means remove one item only
}

// Resulting array with removed element
console.log(array);

Output:

[2, 5, 9]
[2, 9]

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

Statement:
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