Search code examples
javascriptlodash

Comparison of array of objects in the same collection with similar properties


I'm trying to compare each object in the array.

Let's say below is my array:

var objects = [{
        'x': 1,
        'y': 2
    }, {
        'x': 2,
        'y': 1
    },{
        'x': 3,
        'y': 1
    },{
        'x': 4,
        'y': 1
    }];

Given two items, say item1 and item2, I need to check the condition item1.x == item2.y and item1.y == item2.x through the array.

Is there a clean/efficient way to do in Lodash?


Solution

  • 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/[email protected]/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).