How can i remove a specific value from an array in JavaScript ?
eg: arr.remove(x);
In JavaScript, you can use the splice() method to remove a specific value from an array. Here’s an example of how you can do it:
var arr = [1, 2, 3, 4, 5];
var x = 3; // Value to be removed
var index = arr.indexOf(x); // Get the index of the value ‘x’
if (index !== -1) {
arr.splice(index, 1); // Remove 1 element starting from ‘index’
}
console.log(arr); // Output: [1, 2, 4, 5]
In this example, we have an array arr containing [1, 2, 3, 4, 5]. We want to remove the value 3.
Here’s what the code does:
- arr.indexOf(x) finds the index of the value x in the array. If x is not found, it returns -1.
- If the index is not -1 (meaning the value was found), arr.splice(index, 1) removes one element starting from the index where x was found.
After running this code, arr will be [1, 2, 4, 5], as the value 3 has been removed.
Keep in mind that this method modifies the original array. If you want to keep the original array unchanged, you might want to create a copy of it before making any changes.