- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Join every element of an array with a specific character using for loop in JavaScript
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
Advertisements