Remove an element from an array in JavaScript
In this article, we’ll learn how to remove an element from an array in JavaScript. There are multiple ways to remove a specific item from an array using JavaScript.
- Get the last item in an array using JavaScript
- Merge or combine arrays using JavaScript
- Generate a random number in given range using JavaScript
- Animated sticky header on scroll in JavaScript
1. splice() method
In this first approach, we will use the splice() method along with the indexOf() method. First, find the index of an element using the indexOf()
method that you want to remove from an array. After that we have to remove that index using the splice()
method.
const arr = [2, 3, 5, 9];
const index = arr.indexOf(3);
if (index > -1) {
arr.splice(index, 1);
}
console.log(arr);
// Output: [2, 5, 9]
2. filter() method
Using the filter() method, we can easily remove the items from the list. It’s most preferable method to remove an item.
Example 1
let arr = [2, 3, 5, 9];
arr = arr.filter(x => x !== 3);
// Output: [2, 5, 9]
In the next example, you will see the array that contains the list of the object. Let’s remove the specific object from the list using the filter()
method.
Example 2
let arr = [
{
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
},
{
userId: 2,
id: 2,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 3,
title: "fugiat veniam minus",
completed: false
}
];
arr = arr.filter(x => x.userId !== 2);
/* Output:
[
{
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
},
{
userId: 1,
id: 3,
title: "fugiat veniam minus",
completed: false
}
]
*/
That’s it for today.
Thank you for reading. Happy Coding..!!