Home > Mobile >  How to check same property exists in single array of object javascript
How to check same property exists in single array of object javascript

Time:04-09

I would like to know whether array of object has same property value in javascript

for the array object list1,

if name and country has same value, return true

if name same, any object country has value SG return true

if above two conditions fails, return false

var list1=[
  {id:1, name: "sen", country: "IN"},
  {id:2, name: "sen", country: "IN"}
]
const result1=checkObj(list1);

var list2=[
  {id:1, name: "sen", country: "IN"},
  {id:2, name: "sen", country: "SG"}
]
const result2=checkObj(list2);

var list3=[
  {id:1, name: "sen", country: "IN"},
  {id:2, name: "sen", country: "TH"}
]
const result3=checkObj(list3);
Expected Result:
//when passing list1
true
//when passing list2
true
//when passing list3
false

CodePudding user response:

Try this,

var list1=[
  {id:1, name: "sen", country: "IN"},
  {id:2, name: "sen", country: "IN"}
]
const result1=checkObj(list1);

console.log(result1);

var list2=[
  {id:1, name: "sen", country: "IN"},
  {id:2, name: "sen", country: "SG"}
]
const result2=checkObj(list2);

console.log(result2);

var list3=[
  {id:1, name: "sen", country: "IN"},
  {id:2, name: "sen", country: "TH"}
]
const result3=checkObj(list3);

console.log(result3);

function checkObj(list){
  for(i=0;i<list.length;i  )
  {  
   for(j=0;j<list.length;j  )
    {
      if(j!=i){
        if(list[i].name==list[j].name){
          if(list[i].country==list[j].country || list[i].country =='SG'){
          return true;
          }
        }
      }
    }
  }
  return false;
}

CodePudding user response:

In the following snippet I put together an approach based on a single loop over all elements of an array. The occurrences of name/country combinations are collected in a local object o and checked at the end of the function.

const data=[[
  {id:1, name: "sen", country: "IN"},
  {id:2, name: "sen", country: "IN"}
],[
  {id:1, name: "sen", country: "IN"},
  {id:2, name: "sen", country: "SG"},
  {id:1, name: "sen", country: "DN"},
  {id:1, name: "sen", country: "EN"}
],[
  {id:1, name: "sen", country: "IN"},
  {id:2, name: "sen", country: "TH"}
]];

function dupes(arr){
  const o={}, // object o counts all occurrences
    // the sort makes sure the "SG" items come last in ar
    ar= arr.slice(0).sort((a,b)=>a.country==="SG" ? (b.country==="SG" ? 0 : 1) : -1);
  // a single loop over ar:
  ar.forEach(e=>{
   if(e.country!=="SG"){ // "normal" countries:
    let k=e.name "|" e.country;
    o[k]=(o[k]||0) 1
   } else {  // for country=="SG"
    for (let k in o)
     if (k.indexOf(e.name "|")==0)
       o[k]   // increase counts for all elements starting with <el.name>|
   }
  });
  return Object.values(o).some(n=>n>1)
   
}

data.forEach(d=>console.log(dupes(d)))

  • Related