title: Knockout Observable Array with Sorting and Foreach Data-Binding
body: <p>I have an array of objects that are hooked up into a knockout observable array. I needed to apply sorting to these arrays and I ran into some behavior that is a bit confusing.</p>
  
  <p>My first attempt involved applying the sort in the foreach data-binding.<br>
  <a href="http://jsfiddle.net/wnfXV/" rel="noreferrer">http://jsfiddle.net/wnfXV/</a></p>
  
  <p><code>&lt;ul data-bind="foreach: people.sort(function(l,r) { return l.name == r.name ? 0 : (l.name &lt; r.name ? -1 : 1)})"&gt;</code></p>
  
  <p>This performs the proper sorting, but I lose the ability to dynamically add/remove elements from the array and have the DOM update.</p>
  
  <p>If I add a set of parenthesis to access the underlying JavaScript array, everything works fine. </p>
  
  <p><code>&lt;ul data-bind="foreach: people().sort(function(l,r) { return l.name == r.name ? 0 : (l.name &lt; r.name ? -1 : 1)})"&gt;</code></p>
  
  <p>Based on some SO answers I found, I ended up creating a computed observable for the sorted array. 
  <a href="http://jsfiddle.net/wnfXV/2/" rel="noreferrer">http://jsfiddle.net/wnfXV/2/</a></p>
  
  <pre><code>self.sortedPeople = ko.computed(function() {
      return self.people().sort(function(l,r) {
          return l.name == r.name ? 0 : (l.name &lt; r.name ? -1 : 1);
      });
  });
  </code></pre>
  
  <p>This also works. And I don't even need to data-bind to the computed observable since it is executed immediately. I can push and remove array items and the DOM updates appropriately.</p>
  
  <p>However, if I change the code to:</p>
  
  <pre><code>self.sortedPeople = ko.computed(function() {
      return self.people.sort(function(l,r) {
          return l.name == r.name ? 0 : (l.name &lt; r.name ? -1 : 1);
      });
  });
  </code></pre>
  
  <p>Now, I am able to push items to the array and the DOM updates, but the data is not being sorted. </p>
  
  <p>I think these differences are related to knockout dependency tracking, and the difference between operating on an observable array and the native JavaScript array underneath it, but I'm having a hard time conceptualizing why the behavior is changing. I am able to get it to work, but I'm also curious as to what is considered best practice.</p>
  
  <p>Thanks for any help. :)</p>