title: Sorting nested array of objects with dynamic key
body: <p>I am trying to create a sorting function that sorts a nested array of objects while giving a key dynamically (with different depths).</p>
  
  <pre><code>sortByKey(array, key){
      var splitKey = key.split(".");
      if(splitKey.length = 2){
        return array.sort(function(a, b) {
          var x = a[splitKey[0]][splitKey[1]]; var y = b[splitKey[0]][splitKey[1]];
          return ((x &lt; y) ? -1 : ((x &gt; y) ? 1 : 0));
        });
      } else {
        return array.sort(function(a, b) {
          var x = a[key]; var y = b[key];
          return ((x &lt; y) ? -1 : ((x &gt; y) ? 1 : 0));
        });
      }
    }
  </code></pre>
  
  <p>I want to get rid of the <code>if - else</code> and use a <code>for</code> loop instead. The goal is that the function works with 'name', 'name.first' and 'name.first.another' (as an example). Is there a way to do this dynamically?</p>
  
  <p>In other words, I want to use the same function with different arrays. So with one array I want to sort it calling sortByKey(array1, 'name') and with another sortByKey(array2, 'location.address') and maybe with a third sortByKey(array3, 'location.address.postalcode') or something like that.</p>