So, I have an array, and I want to delete a specific element, through .find()
. How should I use it for such purpose?
I know that it should have a condition, let's say
if(element === selectedItem)
{
Array.splice(index,1);
}
but i do not know how to include this into .find()
.
So, I have an array, and I want to delete a specific element, through .find()
. How should I use it for such purpose?
I know that it should have a condition, let's say
if(element === selectedItem)
{
Array.splice(index,1);
}
but i do not know how to include this into .find()
.
- 2 Possible duplicate of How do I remove a particular element from an array in JavaScript? – JJJ Commented Dec 14, 2017 at 10:28
4 Answers
Reset to default 6Removing items from an Array
is not find()
's purpose.
What you want is Array.filter()
.
From MDN Array.prototype.filter:
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Here's an example:
var numbers = [1, 2, 3, 4, 5, 6]
var evenNumbers = numbers.filter(number => {
// returning something that evaluates to `true` will
// keep the item in the result Array
return number % 2 === 0
})
console.log(evenNumbers)
Protip:
Don't instinctively try to posite the Array helper functions you already know into something that does what you want.
Instead, read the MDN Array docs, specifically the 'Methods' section from the sidebar, which already contains a lot of useful methods.
You can use findIndex instead of find:
var data = [
{ id: 1, name: 'Betty' },
{ id: 2, name: 'Mark' },
{ id: 3, name: 'Elizabeth' },
{ id: 4, name: 'Samuel' }
];
var index = data.findIndex(x => x.name === 'Mark');
if (index >= 0)
data.splice(index, 1);
console.log(data);
Let's suppose you have a condition function
, like:
function condition(element) {
return element === selectedItem;
}
Now, you can use find to find the value of the element like this:
var myItem = myArray.find(condition);
And then
myArray.splice(myArray.indexOf(myItem), 1);
However, if your array might have multiple matches to remove, then
var myItem;
while ((myItem = myArray.find(condition)) !== undefined) {
myArray.splice(myArray.indexOf(myItem), 1);
}
To find the index, you need indexOf
and not find
, so that you can perform further operations on top of that.