title: sorting an *ngFor array with trackBy in Angular 4
body: <p>i'm having trouble sorting and array that has a trackBy function. The use case is as follows:</p>
  
  <p>I have an item array. All these items have a z-index property. I also have a layer manager that can edit the z-index of each item. When I want to save my items, I want to sort my array according to the z-index property of each item. I also have a trackBy on my ngFor to limit the amount of change detection on the *ngFor.</p>
  
  <p>With a trackBy function on my *ngFor, the items switch places when I sort the array (which is bad). If I remove the trackBy function this doesn't happen, and the items are sorted according to z-index.</p>
  
  <p><strong>The *ngFor:</strong></p>
  
  <pre><code>&lt;div class="item" *ngFor="let item of items; let i = index;trackBy:getUniqueIdentifier"&gt;
  </code></pre>
  
  <p><strong>The trackBy function:</strong></p>
  
  <pre><code>getUniqueIdentifier(index, item) {
      return this.items.length + ', ' + this.languages._previewLanguage;
  }
  </code></pre>
  
  <p>As you can see, the *ngFor is changed when the length of the items changes or if I switch my language settings. I've tried adding <code>+ ', ' + item.zIndex</code> but this doesn't work.</p>
  
  <p><strong>The sorting function:</strong></p>
  
  <pre><code>sortItemsArrayByZIndex() {
      this.items.sort((i1, i2) =&gt; {
          return (i1.zIndex - i2.zIndex);
      });
  }
  </code></pre>
  
  <p>So it seems that trackBy and this sort function are in conflict for some reason. The result now is that when i use the sort function the the items array gets sorted according to z-index but the items also switch places, which means that their dimensions properties are switched for some reason.</p>
  
  <p>What i want is that the items array is sorted according to z-index but that the items keep their dimensions.</p>
  
  <p>How do i need to change my trackBy function or my sort function so that i get the result that i want?</p>