Sitemap / Advertise

Information



Tags



Share

How to remove elements from an array by value in JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

In this tutorial, I will show you how to remove a specific element in an array, for example, eliminating form options in the user dashboard after an HTML event, by using the splice() method and the indexOf() method in JavaScript.

splice()(1

The splice() method adds/removes items to/from an array, and returns the removed item(s).

This method changes the original array.

indexOf()(2)

The indexOf() method searches the array for the specified item, and returns its position.

The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array.

Returns -1 if the item is not found.

If the item is present more than once, the indexOf method returns the position of the first occurence.

The first item has position 0, the second item has position 1, and so on.

Code

Create the options array with elements.

Add an event listener (click) to the Try button.

In the select_by_value variable, get the index of the selected element in the options array using the indexOf() method.

If the selected element exists, remove the element from the options array executing the splice() method and print a notification message.

Else, print a warning message.


------------ JS ------------

let options = ["password", "email", "new user", "channel", "code", "path", "project", "article", "tool", "gadget", "test"];

document.getElementById("remove").addEventListener("click", () => {
	var select_by_value = options.indexOf("password");
	if(select_by_value > -1){ 
	    options.splice(select_by_value, 1);
	    document.getElementById("test").innerHTML = "Removed Element Index: " + select_by_value;
	}else{
		document.getElementById("test").innerHTML = "Already Removed!";
	}
});

Result:

Options array: ["password", "email", "new user", "channel", "code", "path", "project", "article", "tool", "gadget", "test"]


References

(1) https://www.w3schools.com/jsref/jsref_splice.asp

(2) https://www.w3schools.com/jsref/jsref_indexof_array.asp