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
Release: 2024-12-24 05:53:14
Original
423 people have browsed it

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);
Copy after login

Output:

[2, 5, 9]
[2, 9]
Copy after login

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!

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