Join every element of an array with a specific character using for loop in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Here we are supposed to write a function that takes in two arguments, first an array of String or Number literals, second a String and we have to return a string that contains all the elements of the array prepended and appended by the string.

For example −

applyText([1,2,3,4], ‘a’);

should return ‘a1a2a3a4a’

For these requirements, the array map() method is a better option than the for loop and the code for doing so will be −

Example

const numbers = [1, 2, 3, 4];
const word = 'a';
const applyText = (arr, text) => {
   const appliedString = arr.map(element => {
      return `${text}${element}`;
   }).join("");
   return appliedString + text;
};
console.log(applyText(numbers, word));

Output

The console output for this code will be −

a1a2a3a4a
raja
Published on 18-Aug-2020 07:09:00
Advertisements