1

The pipe has to sort an array of objects by the name property.

sort-by.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {
  private name: string;

  transform(array: Array<any>, args: string[]): Array<any> {
    array.sort((a: any, b: any) => {
      if (a.name < b.name) {
        return -1;
      } else if (a.name > b.name) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}

app.component.html:

 <table>
    <tr *ngFor="let elem of _values | sortBy">
      <td>{{ elem.name }}</td>
      <td>{{ elem.ts }}</td>
      <td>{{ elem.value }}</td>
    </tr>
  </table>

app.module.ts:

//other imports
import { SortByPipe } from './sort-by.pipe';

@NgModule({
  declarations: [
    SortByPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: []
})
export class AppModule { }

The array of objects:

[{
  "name": "t10",
  "ts": 1476778297100,
  "value": "32.339264",
  "xid": "DP_049908"
}, {
  "name": "t17",
  "ts": 1476778341100,
  "value": "true",
  "xid": "DP_693259"
}, {
  "name": "t16",
  "ts": 1476778341100,
  "value": "true",
  "xid": "DP_891890"
}];

It doesn't sort the objects properly, but also doesn't throw any errors.
Maybe there's something wrong with my files?

Any help appreciated!

iHasCodeForU
  • 179
  • 11

2 Answers2

1

The problem is that you are piping the elements and not the array itself.

You should change this

<tr *ngFor="let elem of _values | sortBy">

to this:

<tr *ngFor="let elem of (_values | sortBy)">
Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72
  • @H.Doe whats the result that you are getting? – Pablo Matias Gomez Dec 13 '16 at 16:28
  • It just doesnt sort the array. But I think that the problem is lying somewhere else. The sorting function which ive implemented basically doesnt work. It doesnt sort these properties at all. –  Dec 13 '16 at 16:36
  • I've tested the sort function with the data you posted and works fine for me. Maybe you can put some `console.log`'s to see what happens or even better, debug it. – Pablo Matias Gomez Dec 13 '16 at 16:38
  • When I `console.log` the variable its still unsorted. –  Dec 13 '16 at 17:05
  • This works, previously I had an issue that the _values weren't passed to my pipe filter function. This does exactly that! Sounds like others have an issue with their pipe filter function. – Ben Petersen Mar 16 '17 at 15:57
0

Have you tried adding pure: false?

This makes it so that Angular doesn't care if the input is changed or not

@Pipe({
  name: "sort",
  pure: false
})
Wouter Vanherck
  • 2,070
  • 3
  • 27
  • 41