Home > Net >  Extract the last item which matches the condition
Extract the last item which matches the condition

Time:12-16

I have an array of objects, where I am checking for a boolean property, I need to get the last one from the array of objects which is true and need to get the name property.

This is what I have done, is there any better approach or simple way to achieve this:

const a = [{is_done: true, name: 'a'}, {is_done: true, name: 'b'}, {is_done: false, name: 'c'}]


let output = a.filter(a => a.is_done).slice(-1)[0].name


console.log(output)

CodePudding user response:

You can achieve this by first applying reverse and then using find which will return the first item which corresponds to the condition you specify.

const a = [{is_done: true, name: 'a'}, {is_done: true, name: 'b'}, {is_done: false, name: 'c'}]

const res = a.reverse().find(x => x.is_done);

console.log(res.name)

Please also note that in the near future, you will be able to use findLast and findLastIndex which are currently in stage 3 - https://github.com/tc39/proposals

  • Related