Home > other >  avoid nested loop to find related array items
avoid nested loop to find related array items

Time:08-26

I have this array:

const bases = [ {base: 33, dependsOnBase: 23}, {base: 23, dependsOnBase: 10} ]

now I want to find base that have no dependency. In this case, no base depends on base 33. My solution is

  const total = bases.length;
  let result = null
  for(let i = 0; i<total;i  ){
     let keepBase = true
     for(let j  =  0; j < total; j  ){
          if (ar[i].base == ar[j].dependsOnBase){
            keepBase = false
            continue;
          }
      
     }
     if (keepRecord){
       result= ar[i]
     }
      
  }

 console.log(result)

While it works, it is quite slow with a larger array. How can I achieve a faster result?

CodePudding user response:

Make a Set to hold all the dependencies. Then you can check whether the base is in the set.

const bases = [{
  base: 33,
  dependsOnBase: 23
}, {
  base: 23,
  dependsOnBase: 10
}];

const dependencies = new Set(bases.map(b => b.dependsOnBase));

const result = bases.filter(b => !dependencies.has(b.base));

console.log(result);

CodePudding user response:

Construct a Set of all the dependsOnBase values, then find an item in the array whose base is not included in any of those.

const ar = [{
  base: 33,
  dependsOnBase: 23
}, {
  base: 23,
  dependsOnBase: 10
}];
const allDependsOnBase = new Set(ar.map(({ dependsOnBase }) => dependsOnBase));
const result = ar.find(({ base }) => !allDependsOnBase.has(base));
console.log(result);

  • Related