Harry
Harry

Reputation: 4835

Nested array filter() functions in typescript - always returns true?

I have a very simple function that tests if two lines are intersecting. The intersection function itself works as expected, but when I attempt to use it in nested filter() functions, the outer filter function always returns true:

const intersectingLines: Line[] = poly1Lines.filter(poly1Line => {
    return poly2Lines.filter(poly2Line => {
        return (isIntersecting(poly1Line, poly2Line));
    });
});

I am nesting the filter functions so that I run through all lines in the first polygon testing if it intersects any line in the second (similar to looping over the second array on each iteration of an outer loop over the first array).

I suspected this was happening because the second filter is never returning falsy, so I checked directly for the length of the filtered array, which works as below:

const intersectingLines: Line[] = poly1Lines.filter(poly1Line => {
    const filteredLines = poly2Lines.filter(poly2Line => {
        return (isIntersecting(poly1Line, poly2Line));
    });
    return (filteredLines.length > 0)
});

This feels hacky and less readable than simply nesting the returns of the filters. I'm convinced that I'm nesting the filter functions wrong, but I'm finding little documentation on how to do this. Is there a better way to do this than checking the length of the second filtered array?

Upvotes: 0

Views: 571

Answers (1)

Bergi
Bergi

Reputation: 664307

Indeed, filter always returns an array, which - as an object - is truthy.

The proper solution is not to use .filter(…).length to check whether some of the array elements match a predicate, but to use .some(…):

const intersectingLines: Line[] = poly1Lines.filter(poly1Line =>
    poly2Lines.some(poly2Line => 
        isIntersecting(poly1Line, poly2Line)
    )
);

Upvotes: 2

Related Questions