Main Tutorials

JavaScript – Remove a specified item from array

In JavaScript, we can use the built-in filter() function to remove a specified item from an array.

Table of contents:

1. Remove specified item from the array with filter()

Let’s say we have an array of numbers and want to remove the number 5.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript remove item from array</title>

<script type="text/javascript">

const numbers = [1, 2, 5, 4, 3, 5, 3];

const filteredNumbers = numbers.filter(number => number !== 5);

console.log(filteredNumbers); // Output: [1, 2, 4, 3, 3]

</script>

</head>
<body>
</body>
</html>

output


[1, 2, 4, 3, 3]

The result will contain all the numbers from the original array except for 5.

2. Remove two specified items from the array with filters() and includes()

Let’s say we have an array of numbers and want to remove the numbers 3 and 5.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript remove item from array</title>

<script type="text/javascript">

const numbers = [1, 2, 5, 4, 3, 5, 3];

const itemsToRemove = [3, 5];

const result2 = numbers.filter(number => !itemsToRemove.includes(number));

console.log(result2); // Output: [1, 2, 4]

</script>

</head>
<body>
</body>
</html>

output


[1, 2, 4,]

The result will contain all the numbers from the original array except for 3 and 5.

3. JavaScript examples

Let’s say a list of tasks is stored in an array of objects, each with a unique ID. The user can select multiple tasks to delete by IDs.


const tasks = [
  { id: 1, name: "Write Blog Post" },
  { id: 2, name: "SEO" },
  { id: 3, name: "Clean Database" },
  { id: 4, name: "Take Rest" }
];

const idsToRemove = [2, 4];

const updatedTasks = tasks.filter(task => !idsToRemove.includes(task.id));

console.log(updatedTasks);

Output


[
    {
        "id": 1,
        "name": "Write Blog Post"
    },
    {
        "id": 3,
        "name": "Clean Database"
    }
]

4. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments