Problem
We are required to write a JavaScript function that takes in array of strings, arr, as the first argument and an array of special characters, starters, as the second argument.
The starter array contains characters that can start a comment. Our function should iterate through the array arr and remove all the comments contained in the strings.
For example, if the input to the function is:
const arr = [ 'red, green !blue', 'jasmine, #pink, cyan' ]; const starters = ['!', '#'];
Then the output should be −
const output= [ 'red, green', 'jasmine,' ];
Example
Following is the code −
const arr = [ 'red, green !blue', 'jasmine, #pink, cyan' ]; const starters = ['!', '#']; const removeComments = (arr = [], starters = []) => { const res = []; for(let i = 0; i < arr.length; i++){ let str = '' let flag = true for (let x of arr[i]) { if (starters.includes(x)) { flag = false str = str.replace(/\s+$/, '') } else if (x === '\n') { flag = true } if (flag) str += x }; res.push(str); } return res; }; console.log(removeComments(arr, starters));
Output
Following is the console output −
[ 'red, green', 'jasmine,' ]