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.
In core JavaScript, you can use the indexOf method to find the index of the value you want to remove and then use the splice method to remove it from the array. Here’s an example function to achieve this:
indexOf
splice
Array.prototype.remove = function(value) { var index = this.indexOf(value); if (index !== -1) { this.splice(index, 1); } }; // Example usage: var myArray = [1, 2, 3, 4, 5]; myArray.remove(3); console.log(myArray); // Output: [1, 2, 4, 5]
In this example, indexOf is used to find the index of the specified value in the array. If the value is found (index is not -1), splice is used to remove one element at that index.
value
Please note that modifying the prototype of built-in objects, such as Array, is generally not recommended, as it can lead to unexpected behavior if other code or libraries are also modifying prototypes. In a real-world application, you might want to consider creating a utility function that takes the array as a parameter instead.
Array