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?']
You could use a regex, and then match
each element in the filter
iteration against it.
/[?!.]$/
says match one of these things in the group ([?!.]
) before the string ends ($
).
const arr = ['live.', 'ali!', 'harp', 'sharp%', 'armstrong', 'yep?'];
const re = /[?!.]$/;
const out = arr.filter(el => el.match(re));
console.log(out);
Regarding your comment you can pass in a joined array to the RegExp constructor using a template string.
const query = ['.', '?', '!'];
const re = new RegExp(`[${query.join('')}]$`);
const arr = ['live.', 'ali!', 'harp', 'sharp%', 'armstrong', 'yep?'];
const out = arr.filter(el => el.match(re));
console.log(out);