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.

Updated on: 2026-03-15T23:18:59+05:30

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements