Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract the last item which matches the condition

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Please note that you would probably want to apply the reverse method on a copy of a string and not on the original so it’s better to use [...a] as
hjrshng commented below.

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading