
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Construct Sentence from Array of Words and Punctuations Using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of words and punctuations. 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 word on the left;
there must always be one and only one period at the end of a sentence.
Example
Following is the code −
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));
Output
hey, and, you.
Advertisements