Home > Web Front-end > JS Tutorial > How to Remove an Item from a JavaScript Array by its Value?

How to Remove an Item from a JavaScript Array by its Value?

Barbara Streisand
Release: 2024-12-15 08:09:09
Original
746 people have browsed it

How to Remove an Item from a JavaScript Array by its Value?

Removing Item from Array by Value

To remove an item from a JavaScript array by its value, you can utilize the splice() method in conjunction with the indexOf() method.

For instance, given an array ary = ['three', 'seven', 'eleven']:

var index = ary.indexOf('seven');
ary.splice(index, 1);
Copy after login

Here's how this works:

  1. The indexOf() method searches for the first occurrence of the specified value ('seven' in this case) in the array. If found, it returns its position (index) in the array; otherwise, it returns -1.
  2. If the index is not -1 (i.e., the value was found), the splice() method is used to remove the item from the array. The first parameter of splice() specifies the starting index (the position returned by indexOf()) and the second parameter specifies the number of elements to remove (in this case, 1).

By utilizing this technique, you can efficiently remove items from arrays by their values, allowing you to maintain and modify arrays as needed.

The above is the detailed content of How to Remove an Item from a JavaScript Array by its Value?. 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