Steve Fitzsimons Steve Fitzsimons - 4 years ago 311
TypeScript Question

Angular2 sort array of objects based the order of another array of objects using a pipe

I have a pipe that filters an array based on the objects contained in another array. How do I sort the filtered array (array1) based on the order of the array I am using to filter against (array2)?

import { Injectable, Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'arrayFilter'
})
@Injectable()
export class AttributeFilterPipe implements PipeTransform {
transform(array: any[], filterFrom: any[]): any {
array.filter(item => filterFrom.some(f => f.value == item.value));
}
}

Answer Source

You could utilize the native Array.prototype.sort() method for this:

array.sort((a, b) => {
  let fromValues = filterFrom.map(f => f.value);
  return fromValues.indexOf(a.value) < fromValues.indexOf(b.value) ? -1 : 1;
});

In the snippet above, the fromValue array is created so that we can use the .indexOf() method in order to get the index of an item in the filterFrom array based on a given value. From there, the sort method takes care of the rest and reorders the items in the array array based on the value property relative to the corresponding value's position in the filterFrom array.

You can just chain the .sort() method logic after the .filter() method; just remember to return the result.

import { Injectable, Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'arrayFilter'
})
@Injectable()
export class AttributeFilterPipe implements PipeTransform {
  transform(array: any[], filterFrom: any[]): any {
    return array.filter(item => filterFrom.some(f => f.value === item.value))
                .sort((a, b) => {
                  let fromValues = filterFrom.map(f => f.value);
                  return fromValues.indexOf(a.value) <
                         fromValues.indexOf(b.value) ? -1 : 1;
                });

  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download