Skip to content
Advertisement

How do I return 2 values from two arrays when using filter

I have a Javascript code that uses forEach to loop through each array to check if it fulfils a condition. Then, it calls for another function. Note: by looping through every element in arr1 and arr2, I’m checking if any elements in arr1 are colliding with any elements in arr2. isCollision is a function which calculates their distance if they intersect

arr1.forEach(x => arr2.forEach(y => isCollision(x,y)? explode(x,y): undefined));

Right now, I do not want it to return undefined. So I was wondering is there a way to get the x & y values so that I can map it to another function. I tried this

arr1.filter(x => arr2.filter(y => isCollision(x,y)).map(x,y => //do something)

But right now it’s only returning the value of y. Is there a way for it to return both x and y?

Advertisement

Answer

Try this:

arr1
 .map(x => ({x, y:arr2.find(y => isCollision(x,y)}))
 .filter(pair => pair.y !== undefined)

First map to {x:y} and then remove not found items.

To cast to a non-undefined type, use a another map.

arr1
 .map(x => ({x, y:arr2.find(y => isCollision(x,y)}))
 .filter(pair => pair.y !== undefined)
 .map(pair => pair as {x:Elem, y:Elem})
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement