How can I remove a specific item from an array in JavaScript?

clock icon

asked 2 months ago Asked

message

1 Answers

eye

9 Views

How do I remove a specific value from an array? Something like:

array.remove(value);

Constraints: I have to useĀ core JavaScript. Frameworks are not allowed.

1 Answers

In core JavaScript, you can remove a specific value from an array using the following approach:

Array.prototype.remove = function(value) {
var index = this.indexOf(value);
if (index !== -1) {
this.splice(index, 1);
}
};

var array = [1, 2, 3, 4, 5];
array.remove(3);
console.log(array); // [1, 2, 4, 5]


In the code snippet provided above, a new method `remove` is added to the `Array.prototype` to remove a specific value from the array. The method first finds the index of the value in the array using `indexOf`, and if the value is found (i.e., index is not -1), it removes that element using `splice`.

You can now use the `remove` method on any array to remove a specific value from it.

Write your answer here

Top Questions