title: How to sort a JavaScript array of objects by nested object property?
body: <p>I have this function to sort a JavaScript array of objects based on a property:</p>
  
  <pre><code>// arr is the array of objects, prop is the property to sort by
  var sort = function (prop, arr) {
      arr.sort(function (a, b) {
          if (a[prop] &lt; b[prop]) {
              return -1;
          } else if (a[prop] &gt; b[prop]) {
              return 1;
          } else {
              return 0;
          }
      });
  };
  </code></pre>
  
  <p>It works with arrays like this:</p>
  
  <pre><code>sort('property', [
      {property:'1'},
      {property:'3'},
      {property:'2'},
      {property:'4'},
  ]);
  </code></pre>
  
  <p>But I want to be able to sort also by nested properties, for example something like:</p>
  
  <pre><code>sort('nestedobj.property', [
      {nestedobj:{property:'1'}},
      {nestedobj:{property:'3'}},
      {nestedobj:{property:'2'}},
      {nestedobj:{property:'4'}}
  ]);
  </code></pre>
  
  <p>However this doesn't work because it is not possible to do something like <code>object['nestedobj.property']</code>, it should be <code>object['nestedobj']['property']</code>.</p>
  
  <p><strong>Do you know how could I solve this problem and make my function work with properties of nested objects?</strong></p>
  
  <p>Thanks in advance</p>