early_ninja
early_ninja

Reputation: 119

Comparing two Arrays containing objects in Vanilla JS

I have two object arrays and I need to filter based on the property I have.

   var port = [
      {
         name: 'Cali',
         type:'Mine',
         location = {
            lat: '89.9939',
            lon: '-79.9999'
         }
      },
      {
         name: 'Denver',
         type:'Port',
         location = {
            lat: '67.9939',
            lon: '-85.9999'
         }
      },
      {
         name: 'Seattle',
         type:'Port',
         location = {
            lat: '167.9939',
            lon: '-85.9999'
         }
      },
      ...........
   ]

And have another object as

   var child = [
    {
      lat: '89.9939',
      lon: '-79.9999'
    },

    {
      lat: '67.9939',
      lon: '-85.9999'
     }
     ]

I am using filter

   var result = port.filter( function(el){
                    return    el.location.lat === child.lat
                });

How can i loop for my second array. My data is fairly large in this case.

Upvotes: 1

Views: 115

Answers (1)

kind user
kind user

Reputation: 41893

You could use Array#some to determine if any object from the child array has the same lat value as any object from the port array.

var port = [{name:'Cali',type:'Mine',location:{lat:'89.9939',lon:'-79.9999'}},{name:'Denver',type:'Port',location:{lat:'67.9939',lon:'-85.9999'}},{name:'Seattle',type:'Port',location:{lat:'167.9939',lon:'-85.9999'}}], 
    child = [{lat:'89.9939',lon:'-79.9999'},{lat:'67.9939',lon:'-85.9999'}],
    result = port.filter(el => child.some(v => v.lat == el.location.lat));

    console.log(result);

Upvotes: 1

Related Questions