2

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);
  }
}
2
  • The filtered array (array1) should only contain objects where array1.value === array2.value - comparing objects at the same index? or array1 should only have objects contained in array 2? Commented Feb 3, 2017 at 16:48
  • array1 should only contain objects that are in array2. The comparison should be done on array1[i].value === array2[i].value Commented Feb 3, 2017 at 16:50

1 Answer 1

8

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Option one works but my array has lost its order. Is there any way to filter and keep the order of array1?
So I made a mistake and the array (array1) is staying in the correct order. My problem now is I need the order of array1 to be that of array2
+1 Almost exactly what I wanted but the opposite. I needed to filter an array and pull out all items not within a second array. That code is: return array.filter(item => !filterFrom.some(f => f.value == item.value));

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.