Background
Let's say I have two arrays of objects. Each object in each array should be unique, but sometimes we have the same object in both arrays!
Array 1: [{fruit: "banana"}, {fruit: "orange"}]
Array 2: [{fruit: "apple"}, {fruit: "banana"}, {fruit: "strawberry"}]
Each array has a random number of objects, as you can see.
Objective
Imagine I have a function called isSameObj(obj1, obj2)
that returns true or false depending if ob1 === ob2
or not.
Using this function, I want to know if Array1 has an object repeated in Array2 and vice-versa.
To achieve this, I first started with the traditional for loop.
//assuming Array1.length > Array2.length
for(const obj1 of Array1){
for(const obj2 of Array2){
if(isSameObj(obj1, obj2)){
//do some work
break;
}
}
}
This is the imperative way most of us are used to.
Problem
However, recently I tried functional programming. And I find it incredibly hard to implement this small example functionally!
The closest I got to success was using map
, but map
always traverses the entire array no matter what and I want to stop and break the loop once I find a repeated object.
Some gentlemen suggest to just throw
inside the map, but that really is a solution I would rather avoid. I want to break a loop, not signal an error.
Question
How would I implement this code snippet functionally?