最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use .find() for removing an element from array - Stack Overflow

programmeradmin1浏览0评论

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().

Share Improve this question edited Dec 14, 2017 at 10:55 Eugen-Andrei Coliban asked Dec 14, 2017 at 10:25 Eugen-Andrei ColibanEugen-Andrei Coliban 1,0902 gold badges13 silver badges44 bronze badges 1
  • 2 Possible duplicate of How do I remove a particular element from an array in JavaScript? – JJJ Commented Dec 14, 2017 at 10:28
Add a ment  | 

4 Answers 4

Reset to default 6

Removing 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.

发布评论

评论列表(0)

  1. 暂无评论