JavaScript function to prepend string into all the values of array?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ]
raja
Updated on 21-Nov-2020 10:28:21

Advertisements