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

Why is this filter function not working as expected?

This code:

let rId = requested.map((r) => r._id.toString());
console.log(rId);

let cId = confirmed.map((c) => c._id.toString());
console.log(cId);

rId.filter((r) => !cId.includes(r));
console.log(rId);

Prints this:

[
  '63bcc18d083dd2c66679e160',
  '63bcc331083dd2c66679e278',
  '63bdaef8f115ae565ac564c5'
]

[ '63bdaef8f115ae565ac564c5' ]

[
  '63bcc18d083dd2c66679e160',
  '63bcc331083dd2c66679e278',
  '63bdaef8f115ae565ac564c5'
]

Why is the last item in the array not filtered when the function returns a false statement?

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

What I’m expecting to be printed is this:

[
  '63bcc18d083dd2c66679e160',
  '63bcc331083dd2c66679e278',
  '63bdaef8f115ae565ac564c5'
]

[ '63bdaef8f115ae565ac564c5' ]

[
  '63bcc18d083dd2c66679e160',
  '63bcc331083dd2c66679e278', // <-- item removed
]

>Solution :

Filter does not mutate the array it is called on.

You need to set the result of the filter to a value;

rId = rId.filter((r) => !cId.includes(r));
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