Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Join every element of an array with a specific character using for loop in JavaScript
In JavaScript, you can join array elements with a specific character using a for loop. This approach gives you fine control over how elements are combined and what separators or wrappers to use.
Problem Statement
We need to create a function that takes an array and a string, then returns a new string where each array element is wrapped by the given string. For example:
applyText([1,2,3,4], 'a') should return 'a1a2a3a4a'
Using for Loop Approach
Here's how to solve this using a for loop to iterate through the array:
const applyTextWithLoop = (arr, text) => {
let result = text; // Start with the text
for (let i = 0; i
a1a2a3a4a
Alternative: Using Array.map() Method
While the for loop works well, the array map() method provides a more functional approach:
const applyText = (arr, text) => {
const appliedString = arr.map(element => {
return `${text}${element}`;
}).join("");
return appliedString + text;
};
const numbers = [1, 2, 3, 4];
const word = 'a';
console.log(applyText(numbers, word));
a1a2a3a4a
Comparison
| Method | Readability | Performance | Use Case |
|---|---|---|---|
| For Loop | Good | Slightly faster | Simple iteration and concatenation |
| Array.map() | Excellent | Good | Functional programming style |
Example with Different Data Types
// With strings const fruits = ['apple', 'banana', 'cherry']; console.log(applyTextWithLoop(fruits, '-')); // With mixed data const mixed = [1, 'hello', true, 3.14]; console.log(applyTextWithLoop(mixed, '|'));
-apple-banana-cherry- |1|hello|true|3.14|
Conclusion
Both for loops and array methods can join elements with specific characters. For loops offer direct control and slightly better performance, while array methods like map() provide cleaner, more readable code for functional programming approaches.
