There couple of different ways how to remove specific item from JavaScript array. Here we will explain how to use:
- JavaScript Array pop() function
- JavaScript Array shift() function
- JavaScript Array splice() function
- JavaScript Array filter() function
Remove last element from Array
Using .pop()
method we can remove last element from array
<script>
let arrayNumbers = ["one", "two", "three", "four"];
arrayNumbers.pop();
// output: "one", "two", "three"
</script>
Remove first element from array
Using .shift()
method we can remove first element from array
<script>
let arrayNumbers = ["one", "two", "three", "four"];
arrayNumbers.shift();
//output [ "two", "three", "four"]
</script>
Remove element from a specific index
Using .splice()
method it is possible to remove array element from specific position
<script>
let arrayNumbers = ["one", "two", "three", "four"];
arrayNumbers.splice(2,1);
// output ["one", "two", "four"];
</script>
.splice(2,1)
=> will remove 1 element from second position (counts from zero)
Following same logic we can remove two elements starting from position 1:
<script>
let arrayNumbers = ["one", "two", "three", "four"];
arrayNumbers.splice(1,2);
// output: ["one", "four"];
</script>
Remove element from array by value
Using .filter()
method we can remove element by value
<script>
let elRemove = "three";
let arrayNumbers = ["one", "two", "three", "four"];
arrayNumbers = arrayNumbers.filter(item => item !== elRemove);
// output ["one", "two", "four"];
</script>
using the same filter we can remove multiple elements by values
<script>
let elRemove = ["one","three"];
let arrayNumbers = ["one", "two", "three", "four"];
arrayNumbers = arrayNumbers.filter(item => !elRemove.includes(item))
// output ["two", "four"];
</script>