admin管理员组文章数量:1316980
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.
本文标签: javascriptUse find() for removing an element from arrayStack Overflow
版权声明:本文标题:javascript - Use .find() for removing an element from array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742012436a2413138.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论