Constructing a sentence based on array of words and punctuations using JavaScript

We need to write a JavaScript function that takes an array of words and punctuations and constructs a proper sentence following specific spacing and punctuation rules.

Problem Statement

Our function should join array elements to construct a sentence based on the following rules:

  • There must always be a space between words

  • There must not be a space between a comma and the word on the left

  • There must always be one and only one period at the end of a sentence

Solution

Here's how we can implement the sentence builder function:

const arr = ['hey', ',', 'and', ',', 'you'];

const buildSentence = (arr = []) => {
   let res = '';
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      const next = arr[i + 1];
      
      if(next === ','){
         res += el;
      } else {
         if(!next){
            res += `${el}.`;
         } else {
            res += `${el} `;
         }
      }
   }
   return res;
};

console.log(buildSentence(arr));
hey, and, you.

How It Works

The algorithm processes each element in the array and checks the next element to determine proper spacing:

  • If the next element is a comma, add the current element without a space

  • If there's no next element, add the current element with a period

  • Otherwise, add the current element followed by a space

Alternative Approach

Here's a more concise solution using array methods:

const buildSentenceAlt = (arr = []) => {
   return arr.reduce((sentence, word, index) => {
      const nextWord = arr[index + 1];
      
      if (nextWord === ',') {
         return sentence + word;
      } else if (index === arr.length - 1) {
         return sentence + word + '.';
      } else {
         return sentence + word + ' ';
      }
   }, '');
};

const testArray = ['hello', ',', 'world', ',', 'how', 'are', 'you'];
console.log(buildSentenceAlt(testArray));
hello, world, how are you.

Conclusion

Both approaches effectively construct proper sentences by checking adjacent elements and applying spacing rules. The reduce method offers a more functional programming approach while the for loop provides clearer step-by-step logic.

Updated on: 2026-03-15T23:19:00+05:30

883 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements