WebMasterCampus
WEB DEVELOPER Resources

Javascript Remove Single or All Specified Element From an Array

Learn how to remove single or all specified element from an array in Javascript.


Javascript Remove Single or All Element From an Array

Sometimes we need to remove a single value or all values from an array. We can achieve this by using different ways. However, the most efficient and easiest method by using Javascript splice method.

The following code will remove first instance of number 9 from array.

Remove Single Element from array


var number_array = [9, 8, 7, 6, 9, 5, 4, 9, 3, 9];
var removeNo = 9;

array_index = number_array.indexOf(removeNo);

if (array_index > -1) {
   array.splice(array_index, 1);
}
console.log(number_array);

The following code will remove all instances of number 9 from array.

Remove Multiple Elements from array


var number_array = [9, 8, 7, 6, 9, 5, 4, 9, 3, 9];
var removeNo = 9;

console.log(array);

array_index = number_array.indexOf(removeNo);

while(array_index > -1){

   number_array.splice(array_index, 1);

   array_index = number_array.indexOf(removeNo);
}

// array = [8, 7, 6, 5, 4, 3];
console.log(number_array);

The following code will remove all instances of number 9 from array but this is also compatible with ECMAScript 6.

Using Javascript filter function you can return an array with all elements that is not equal to your specified number you want to remove.

Remove All specifield Elements from array using ECMAScript 6

let number_array = [9, 8, 7, 6, 9, 5, 4, 9, 3, 9,3,3];
let removeNo = 9;


number_array = number_array.filter(item => item !== removeNo);

console.log(number_array);
Created with love and passion.