How to Delete User Input Values from an Array in JavaScript?

Estimated read time 2 min read

In JavaScript, you can remove user input values from an array using the splice() method or the filter() method. Here’s an example of how to use both methods:

// Example array of numbers
const numbers = [1, 2, 3, 4, 5];

// User input value to remove
const userInput = 3;

// Remove the user input value using splice()
const index = numbers.indexOf(userInput); // Get the index of the user input value
if (index !== -1) {
  numbers.splice(index, 1); // Remove the element at the given index
console.log(numbers); // Output: [1, 2, 4, 5]

// Remove the user input value using filter()
const filteredNumbers = numbers.filter(num => num !== userInput);
console.log(filteredNumbers); // Output: [1, 2, 4, 5]

In this example, the user input value is 3, and we want to remove it from the numbers array. First, we use the indexOf() method to find the index of the user input value in the array. If the index is not -1 (meaning the value was found), we use the splice() method to remove the element at that index.

Alternatively, we can use the filter() method to create a new array that excludes the user input value. The filter() method creates a new array with all elements that pass the test implemented by the provided function. In this case, the function is checking if the element is not equal to the user input value.

Both methods achieve the same result of removing the user input value from the array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply