Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and remove first matching element in an array of Javascript objects

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.

like image 770
Gazzer Avatar asked Nov 29 '18 08:11

Gazzer


Video Answer


1 Answers

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);
like image 200
Mamun Avatar answered Sep 22 '22 08:09

Mamun