1

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));
  }
}

1 Answer 1

1

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;
                });

  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.