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

How to Check All Array Element Inside endswith()

let array1 = ["?", "!", "."];
let array2 = ["live.", "ali!", "harp", "sharp%", "armstrong","yep?"];

console.log(array2.filter((x) => x.endsWith("?")));

The output is just: ['yep?']

Because the function endsWith() only checked for "?" as you see in the code.
How do I loop the elements on the array1 (suffixes) inside the endsWith function so the output is:

['live.', 'ali!', 'yep?']

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 use an inner .some() call to loop over your array1 and return true from that when you find a match instead of hardcoding the ?:

const array1 = ["?", "!", "."];
const array2 = ["live.", "ali!", "harp", "sharp%", "armstrong","yep?"];

const res = array2.filter((x) => array1.some(punc => x.endsWith(punc)));
console.log(res);

Above, when you return true (or a truthy value) from the .some() callback, the .some() method will return true, otherwise it will return false if you never return true, thus discarding it.

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