Sort Array By Another Array Pipe?

#1

Hello,

I hope all of you are fine and doing well,

I need a Pipe that sort Array1 by id using OrderArray.

HTML = " <ng-container *ngFor="let item of items | sortBy : ‘id’>

Array1:
[{“id”: 1,“title”: “Post-1”,“thumb”: “post1.png”},
{“id”: 2,“title”: “Post-2”,“thumb”: “post2.png”},
{“id”: 3,“title”: “Post-3”,“thumb”: “post3.png”},
{“id”: 4,“title”: “Post-4”,“thumb”: “post4.png”},
{“id”: 5,“title”: “Post-5”,“thumb”: “post5.png”}]

OrderArray:
[3, 5, 2, 4, 1]

I need the result to be:
Result:
[{“id”: 3,“title”: “Post-3”,“thumb”: “post3.png”},
{“id”: 5,“title”: “Post-5”,“thumb”: “post5.png”},
{“id”: 2,“title”: “Post-2”,“thumb”: “post2.png”},
{“id”: 4,“title”: “Post-4”,“thumb”: “post4.png”},
{“id”: 1,“title”: “Post-1”,“thumb”: “post1.png”},]

Hope I’ll find someone to help, I tried a lot without success.

Thanks

#2

The Solution is:

`@Pipe({name: “sortBy”})
export class SortPipe {
transform(array: Array, args: string): Array {
// OrderArray
let sequence = [3, 5, 2, 4, 1];
if (array !== undefined) {
array.sort( function (a, b) {
var A = a[args], B = b[args];

  if (sequence.indexOf(A) < sequence.indexOf(B)) {
    return 1;
  } else {
    return -1;
  }
  
});
}
console.log(array);
return array;

}
}`

#3

This should be done in the controller, not via a pipe. See here for more details.