Steve Fitzsimons
Steve Fitzsimons

Reputation: 3904

Angular2 filtering array of objects based on an array of objects using pipe

I'm struggling to get my head around how to filter an array of objects based on another array of objects using the angular pipe. What i have so far is a pipe that filters based on a single argument.

I have 2 arrays, array1 and array 2, which both contain complex objects. The filtered array (array1) should only contain objects where array1.value === array2.value

My code so far:

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 => item.value.indexOf(filterFrom[0].value) !== -1);
  }
}

Upvotes: 2

Views: 22174

Answers (1)

tymeJV
tymeJV

Reputation: 104785

If array 1 should only contain objects that are in array 2:

return array.filter(item => filterFrom.some(f => f.value == item.value));

If array 1 should only contain objects that are in array 2 at the same index:

return array.filter((item, index) => item.value == filterFrom[index].value);

Upvotes: 8

Related Questions