Suppose I have an array:
members = [
{name: 'Anna', class: 'one'},
{name: 'Bob', class: 'two'},
{name: 'Chuck', class: 'two'}];
removed = members.myRemoveByClass('two'); //something like
// removed is {name: 'Bob', class: 'two'}
// members is [{name: 'Anna', class: 'one'}, {name: 'Chuck', class: 'two'}]
I'm looking for something for myRemoveByClass. ES2015 is fine or using Lodash. The array will have been ordered already. None of the questions I've seen quite match what I'm looking for.
You can use Array.prototype.findIndex():
The
findIndex()method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating no element passed the test.
Then splice() the object by that index.
var members = [
{name: 'Anna', class: 'one'},
{name: 'Bob', class: 'two'},
{name: 'Chuck', class: 'two'}];
var idx = members.findIndex(p => p.class=="two");
var removed = members.splice(idx,1);
console.log(removed);
console.log(members);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With