How to remove a specific element from an array in JavaScript
You can use the splice() method to remove elements from an array at any index. The syntax for removing an element from an array is as follows: splice(startIndex, deleteCount)
.
Here, the startIndex parameter specifies the index at which to start processing the array; the second deleteCount parameter is the number of elements to delete (if set to 0, no element will be deleted). Let’s look at the following example to understand how this works:
Example 1: How to remove a specific element from an array in JavaScript
var persons = ["Yohan", "Thomas", "Jean", "Bob", "Alex"]; removed = persons.splice(2,2); // Removes the third and fourth element console.log(persons); // ["Yohan", "Thomas", "Alex"] console.log(removed); // ["Jean", "Bob"] console.log(removed.length); //2
Output:
["Yohan", "Thomas", "Alex"] ["Jean", "Bob"] 2[st_adsense]
Example 2: How to remove a specific element from an array in JavaScript
var colors = ["Blue", "Green", "Black", "Gray", "Red"]; removed = colors.splice(2,1); // Removes the third element console.log(colors); // ["Blue", "Green", "Gray", "Red"] console.log(removed); // ["Black"] console.log(removed.length); // 1
Output:
["Blue", "Green", "Gray", "Red"] ["Black"] 1
Example 3: How to remove a specific element from an array in JavaScript
var language = ["Python", "JavaScript", "JQuery", "Java", "PHP"]; removed = language.splice(2); // Remove all items from index 2 console.log(language); // ["Python", "JavaScript"] console.log(removed); // ["JQuery", "Java", "PHP"] console.log(removed.length); // 3
Output:
["Python", "JavaScript"] ["JQuery", "Java", "PHP"] 3[st_adsense]
How to remove a specific element from an array using Javascript / ECMAScript 6:
In the example below, we use the array.filter(…) function to remove unwanted elements from the array. This function does not change the original array and creates a new one. If your browser does not support this feature (for example, Internet Explorer before version 9 or Firefox before version 1.5), try using Mozilla’s polyfill filter.
let nbr = 6 var arr = [3, 6, 8]; arr = arr.filter(item => item !== nbr) //remove 6 from the array console.log(arr)
Output:
[3, 8][st_adsense]