0

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)
      }
      
  }
Abhishek Mishra
  • 340
  • 4
  • 14
  • You'll need to `map()` on `arr2` to test `includes()` like that. The second array absolutely does not include the value `269292`, that's buried in an object. – tadman Jul 31 '23 at 16:46
  • Why not make a look-up table for this, rework `arr2` into an object with the `VILLAGE_ID` as the key? Then you can do `villages[x.VI_ID]` and get the object, if any, that matches. – tadman Jul 31 '23 at 16:48
  • Does this answer your question? [Check if object value exists within a Javascript array of objects and if not add a new object to array](https://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add) – Heretic Monkey Jul 31 '23 at 17:01

2 Answers2

1

Replace the condition with this one:

if (arr2.some(sth=> sth.VILLAGE_ID === arr1[i].VI_ID)) {
    ...
  }
Byte Ninja
  • 881
  • 5
  • 13
0

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);
MarkBeras
  • 459
  • 1
  • 3
  • 13