How to remove a specific item from an array?

September 28, 2022 No comments js array remove tips solutions javascript

Introduction

In JavaScript, we may need to remove a specific item from an array.

In this post, we'll learn how to remove an item from an array.

How to remove a specific item from an array

In vanilla JS, to remove a specific item from an array we need to find the index of that element using the indexOf method, and then remove that index with the splice method.

const array = [8, 5, 2, 0, 9];

const index = array.indexOf(5); // index of 5
if (index > -1) { // only splice array when our item is found
  array.splice(index, 1); // second parameter means how many items we want to remove
}

console.log(array);  // array = [8, 2, 0, 9]

Conclusion

To remove a specific item from an array in vanilla JS, we use the indexOf and splice methods.

In ES6 we can use array.filter(...) method to remove items from an array.

In jQuery we can use array.grep(...) method to remove item/items from an array.

{{ message }}

{{ 'Comments are closed.' | trans }}