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

  • A+
Category:Languages

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 could create your own Array class:

 class Members extends Array {    removeByClass(className) {      for(const [index, member] of this.entries())         if(member.class === className)             return this.splice(index, 1)[0];    } } 

Use it as

 const members = new Members([ {/*...*/}, {/*...*/} ]);  members.removeByClass("..."); 

PS: "class" is a very bad name as it is a reserved keyword

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: