How to write a JavaScript function that returns true if a portion of string 1 can be rearranged to string 2?


We have to write a function that returns true if a portion of string1 can be rearranged to string2. Write function, say scramble(str1,str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

For example −

Let’s say string1 is str1 and string2 is str2.
str1 is 'cashwool' and str2 is ‘school’ the output should return true.
str1 is 'katas' and str2 is 'steak' should return false.

So, here is the code for doing this. We simply split and sort the two strings and then check whether the smaller string is a substring of the larger one or not.

The full code for doing so will be −

Example

const str1 = 'cashwool';
const str2 = 'school';
const scramble = (str1, str2) => {
   const { length: len1 } = str1;
   const { length: len2 } = str2;
   const firstSortedString = str1.split("").sort().join("");
   const secondSortedString = str2.split("").sort().join("");
   if(len1 > len2){
      return firstSortedString.includes(secondSortedString);
   }
   return secondSortedString.includes(firstSortedString);
};
console.log(scramble(str1, str2));

Output

The output in the console will be −

true

Updated on: 20-Aug-2020

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements