skip to Main Content

I have two arrays-

var arr1=  [
{
  VILLAGES_NAME: 'Chozuba Vill.',
  VI_ID: 269292,
  VI_SUBDIST_ID: 1806
},
{
  VILLAGES_NAME: 'Thevopisu',
  VI_ID: 269381,
  VI_SUBDIST_ID: 1806
},
{
  VILLAGES_NAME: 'Chozubasa (UR)',
  VI_ID: 269293,
  VI_SUBDIST_ID: 1806
}
  ];



let arr2=[
{
  LOCALITIES_NAME: 'CHOZUBA PART TWO',
  LOCALITY_ID: 301,
  VILLAGE_ID: 269292
},
{
  LOCALITIES_NAME: 'CHOZUBA PART ONE',
  LOCALITY_ID: 300,
  VILLAGE_ID: 269292
}
  ];

I want to check while looping arr1 if value of VI_ID of arr1 is matching anywhere in VILLAGE_ID of arr2.

This is what I have tried till now but not getting expected result.

 for(let i=0;i<arr1.length;i++)
  {
      if(arr2.includes(arr1[i].VI_ID))
      {
           console.log(arr1[i].VILLAGES_NAME)
      }
      
  }

2

Answers


  1. You can’t do it with only one for loop without changing one of the arrays type. For example:

    var arr1 = [
      {
        VILLAGES_NAME: 'Chozuba Vill.',
        VI_ID: 269292,
        VI_SUBDIST_ID: 1806
      },
      {
        VILLAGES_NAME: 'Thevopisu',
        VI_ID: 269381,
        VI_SUBDIST_ID: 1806
      },
      {
        VILLAGES_NAME: 'Chozubasa (UR)',
        VI_ID: 269293,
        VI_SUBDIST_ID: 1806
      }
    ];
    
    let arr2 = [
      {
        LOCALITIES_NAME: 'CHOZUBA PART TWO',
        LOCALITY_ID: 301,
        VILLAGE_ID: 269292
      },
      {
        LOCALITIES_NAME: 'CHOZUBA PART ONE',
        LOCALITY_ID: 300,
        VILLAGE_ID: 269292
      }
    ];
    
    const villageIdSet = new Set(arr2.map(item => item.VILLAGE_ID));
    
    const matchedItems = arr1.filter(item => villageIdSet.has(item.VI_ID));
    
    console.log(matchedItems);
    
    Login or Signup to reply.
  2. Replace the condition with this one:

    if (arr2.some(sth=> sth.VILLAGE_ID === arr1[i].VI_ID)) {
        ...
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search