var objects = [
{'x': 1, 'y': 2},
{'x': 2, 'y': 1},
{'x': 3, 'y': 1},
{'x': 4, 'y': 1}
];
var comparedLodash = _.map(objects, function (item) {
return !!_.find(objects, {x: item.y, y: item.x});
});
console.log(comparedLodash);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
Complexity of this is O(n^2).
Note: You could make it O(nlogn) if you sorted the array before starting the comparison, but this would add significant noise to the code.
Breakdown:
The _.map(somearray, somefunction)
function executes the somefunction
into every element of somearray
. We will use it to convert every item of the objects
array into a boolean. Roughly it is like:
var comparedLodash = _.map(objects, functionThatWillConvertAnItemIntoABoolean);
Now, each item1
should be converted true
if there's anotherItem
with item1.x == anotherItem.y
and item1.y == anotherItem.x
. To find if this another item exists, we use _.find()
.
_.find(somearray, someobject)
tries to if the someobject
exists in the somearray
. That is why we do, above, something like:
function (item) {
var anotherItem = {x: item.y, y: item.x}
return _.find(objects, anotherItem);
}
Lastly, _.find
returns the object, if found, and undefined
if not found. We use !!
to convert that to boolean (!!undefined
becomes false
and !!someobject
becomes true
).