Validating string with reference to array of words using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a sequence of valid words and a string. Our function should test if the string is made up by one or more words from the array.

Input

const arr = ['love', 'coding', 'i'];
const str = 'ilovecoding';

Output

const output = true;

Because the string can be formed by the words in the array arr.

Example

Following is the code −

 Live Demo

const arr = ['love', 'coding', 'i'];
const str = 'ilovecoding';
const validString = (arr = [], str) => {
   let arrStr = arr.join('');
   arrStr = arrStr
   .split('')
   .sort()
   .join('');
   str = str
   .split('')
   .sort()
   .join('');
   const canForm = arrStr.includes(str);
   return canForm;
};
console.log(validString(arr, str));

Output

true
raja
Published on 17-Apr-2021 11:45:28
Advertisements