@toddDec 02.2022 — #To remove a specific value from an array in JavaScript, you can use the Array.prototype.filter() method. This method creates a new array with all elements that pass the test implemented by the provided function. In this case, the function should check whether the element is equal to the value you want to remove, and return false if it is. Here is an example:
const array = [1, 2, 3, 4, 5];
// Create a new array with all elements that are not equal to 3. const newArray = array.filter(element => element !== 3);
console.log(newArray); // Output: [1, 2, 4, 5]
This code uses the filter() method to create a new array with all elements that are not equal to 3. The resulting array is assigned to the newArray variable, which contains the elements 1, 2, 4, and 5. The original array is not modified by the filter() method.
Alternatively, you can use the Array.prototype.indexOf() and Array.prototype.splice() methods to remove the value from the array. The indexOf() method finds the index of the first occurrence of the value in the array, and the splice() method is used to remove that element at the specified index. Here is an example:
const array = [1, 2, 3, 4, 5];
// Find the index of the first occurrence of 3 in the array. const index = array.indexOf(3);
// If the value is found in the array, remove it. if (index !== -1) { array.splice(index, 1); }
console.log(array); // Output: [1, 2, 4, 5]
This code uses the indexOf() method to find the index of the first occurrence of 3 in the array. If the value is found, the splice() method is used to remove the element at that index. The resulting array contains the elements 1, 2, 4, and 5, and the original array is modified by the splice() method.
Both of these approaches are effective ways to remove a specific value from an array in JavaScript. Which method you choose will depend on your specific needs and preferences.