Sometimes, we want to remove item from array using its name / value with JavaScript.
In this article, we’ll look at how to remove item from array using its name / value with JavaScript.
How to remove item from array using its name / value with JavaScript?
To remove item from array using its name / value with JavaScript, we can use the JavaScript array’s findIndex and splice methods.
For instance, we write:
const countries = [{
id: 'AF',
name: 'Afghanistan'
},
{
id: 'AL',
name: 'Albania'
},
{
id: 'DZ',
name: 'Algeria'
}
];
const index = countries.findIndex(c => c.id === 'AF')
countries.splice(index, 1)
console.log(countries)
We call countries.findIndex with a callback that finds the entry with id set to 'AF'.
Then we call splice with the index found and 1 to remove the entry with the given index.
Therefore, countries is now:
[
{
"id": "AL",
"name": "Albania"
},
{
"id": "DZ",
"name": "Algeria"
}
]
according to the console log.
Conclusion
To remove item from array using its name / value with JavaScript, we can use the JavaScript array’s findIndex and splice methods.