Validating string with reference to array of words using JavaScript


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

Updated on: 17-Apr-2021

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements