Checking if string characters can be arranged to form another string I am working on a code project that checks if all the characters in str1 can be arranged to form another string (str2).  If all the characters in str2 are present in str1 (including any repeated characters in str2, i.e. if str2 has two 'a' characters, str1 must correspondingly have two as well), then the function returns true.

For example, here are some test cases below and the intended return:




str1 = 'rkqodlw'
str2 = 'world'
Expected: true

str1 = 'cedewaraaossoqqyt'
str2 = 'codewars'
Expected: true

str1 = 'katas'
str2 = 'steak'
Expected: false

str1 = 'scriptjava'
str2 = 'javascript'
Expected: true



I have a working code solution, but I'd like to refactor for optimal performance as there are a quite a number of random tests (of unknown length) that the code must test against and my code isn't completing the tests in the recommended timeframe.



function stringscrambling(str1, str2) {
  var arr1 = str1.split('');
  var arr2 = str2.split('');
  var index;
  var l = arr2.length;

  while (l--) {
    index = arr1.indexOf(arr2[l]);
    if (index &gt; -1) {
      arr1.splice(index, 1);
    } else { 
    return false;
    };
  }
  return true;
}


I originally used a basic for loop (with the array length cached as a variable and not in the for statement) as follows:

for (var i = 0, l = arr2.length; i &lt; l ; i++) {
    index = arr1.indexOf(arr2[i]);
    if (index &gt; -1) {
      arr1.splice(index, 1);
    } else { 
      return false;
    };
  }
  return true;
 }


but tried the while-loop in reverse as I read that specific looping would offer a bit better in terms of benchmarked performance. The change in loop offered a negligible performance upgrade.

Are there any other specific tricks I can implement on my code that can speed it up and still retain the original functionality?
The way to improve your performance is to use a better algorithm, specifically, sort both strings and compare:

function stringscrambling(str1, str2) {
 var sort1 = str1.split('').sort().join('');
 var sort2 = str2.split('').sort().join('');

 return sort1 === sort2;
}