Can part of a string be rearranged to form another string in JavaScript


Problem

We are required to write a JavaScript function that takes in two strings, str1 and str2. Our function should return true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

Example

Following is the code −

 Live Demo

const str1 = 'rkqodlw';
const str2 = 'world';
const canForm = (str1 = '', str2 = '') => {
   if(str1.length < str2.length){
      return false;
   };
   const res = str2.split('');
   str1.split("").forEach(val => {
      if(res.includes(val)){
         res.splice(res.indexOf(val), 1);
      };
   });
   return res.length === 0;
};
console.log(canForm(str1, str2));

Output

Following is the console output −

true

Updated on: 19-Apr-2021

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements