Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

distinct objects between two arrays based on a property - lodash

Is there a direct method to get distinct objects into a new array based on object's property from two different arrays ?

Currently looping through first array and then comparing with each object in second array to maintain a counter and push into new array, when distinct.

   var newArray = [];
   _.each(firstArray, function(item) {               //loop items in 1st []
      var count = 0;        
     _.each(secondArray, function(secondItem) {
       if(secondItem.property = item.property) {      
        count++
       }
     }  
  if(count == 0)   newArray.push(item); //push distinct item into new []
  }

example Data :

var array1 = [{id:1, busNum: "1234"}, {id:2, busNum:"4567"}]
var array2 = [{id:1, busNum: "2344"}, {id:2, busNum:"1234"}]

want to eliminate common buses (ones with same bus number)

  var newArray = [{id:2, bus:"4567"}, {id:1, bus:"2344"]
like image 511
Rk R Bairi Avatar asked Oct 21 '25 03:10

Rk R Bairi


1 Answers

You could use _.xorBy for a symmetric difference.

var array1 = [{id:1, busNum: "1234"}, {id:2, busNum:"4567"}],
    array2 = [{id:1, busNum: "2344"}, {id:2, busNum:"1234"}],
    result = _.xorBy(array1, array2, 'busNum');

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
like image 192
Nina Scholz Avatar answered Oct 24 '25 11:10

Nina Scholz