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
Selected Reading
Convert JavaScript array iteration result into a single line text string
Let's say we have a string and an array of keywords to search for:
const textString = 'Convert javascript array iteration result into a single line text string. Happy searching!'; const keywords = ['integer', 'javascript', 'dry', 'Happy', 'exam'];
We need to write a function that maps the array to a string containing only true and false values, depending on whether each array element is present in the string or not.
Solution Using reduce() and join()
The most efficient approach uses reduce() to build an array of boolean values, then join() to convert it into a single line string:
const textString = 'Convert javascript array iteration result into a single line text string. Happy searching!';
const keywords = ['integer', 'javascript', 'dry', 'Happy', 'exam'];
const includesString = (arr, str) => {
return arr.reduce((acc, val) => {
return acc.concat(str.includes(val));
}, []).join(', ');
};
console.log(includesString(keywords, textString));
false, true, false, true, false
Alternative Method Using map() and join()
A more readable approach uses map() to transform each element, then join() to create the string:
const includesStringMap = (arr, str) => {
return arr.map(keyword => str.includes(keyword)).join(', ');
};
console.log(includesStringMap(keywords, textString));
false, true, false, true, false
How It Works
The function checks each keyword against the text string:
-
'integer'?false(not found in text) -
'javascript'?true(found in text) -
'dry'?false(not found in text) -
'Happy'?true(found in text, case-sensitive) -
'exam'?false(not found in text)
Comparison
| Method | Readability | Performance | Use Case |
|---|---|---|---|
reduce() |
Good | Slightly slower | When you need more control over accumulation |
map() |
Better | Faster | Simple transformations (recommended) |
Conclusion
Both methods effectively convert array iteration results into a single line string. The map() approach is more readable and intuitive for simple transformations like this.
Advertisements
