Suppose, we have an array of string literals like this −
const arr = ["a", "b", "c"];
What we want is that we have a string that let say "Hello" and we want to prepend this string to each and every value of the array.
Therefore, our function should take one array of strings as the first argument and a single string as the second argument.
Then the function should prepend the second argument string to each element of the array.
We should also insert a separator ("_" in our case) between the two values.
Therefore, our output should look like −
const output = ["Hello_a", "Hello_b", "Hello_c"];
Example
The code for this will be −
const arr = ["a", "b", "c"]; const prependLiteral = (arr = [], str = '') => { for(let i = 0; i < arr.length; i++){ arr[i] = `${str}_` + arr[i]; }; return arr.length; }; prependLiteral(arr, 'Hello'); console.log(arr);
Output
And the output in the console will be −
[ 'Hello_a', 'Hello_b', 'Hello_c' ]