简体   繁体   中英

My loop isn't separating the array items that don't match on the other array, how can I do that?

I`m trying to.push() the array items on both arrays, that don't match on each other and then assign it to the new array empty that I've created.. but it just iterate and return 60 items repeated.

What am I doing wrong?

Note: I'm still studying that subject, so I'm sorry if what I am doing is dumb haha

const bobsFollowers = ['James', 'Caleb', 'Rita', 'Samantha'];
const tinasFollowers = ['Maurice', 'Caleb', 'Samantha'];
const mutualFollowers = [];
const notMutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++) {
  for (let j = 0; j < tinasFollowers.length; j++) {
    if (bobsFollowers[i] === tinasFollowers[j]) {
      mutualFollowers.push(tinasFollowers[j]);
    }
    for (let x = 0; x < tinasFollowers.length && bobsFollowers.length; x++) {
      if (bobsFollowers[i] !== tinasFollowers[j] && tinasFollowers[j] !== bobsFollowers[i])
    notMutualFollowers.push(bobsFollowers[i], tinasFollowers[j]);
    } 
  }
}

console.log(mutualFollowers);
console.log(notMutualFollowers);

I thing that is. Ojs: I like define a const like currentValue just to make more sense and make understanding easier.

for (let i = 0; i < bobsFollowers.length; i++) {
  const currentName = bobsFollowers[i];
  let isHaveSomeInArray = false;
    
  for (let j = 0; j < tinasFollowers.length; j++) {
    const currentComparation = tinasFollowers[j];

    if (currentName === currentComparation) {
      mutualFollowers.push(currentComparation);
      isHaveSomeInArray = true;
    }
  }

 if (!isHaveSomeInArray) {
     notMutualFollowers.push(currentName);
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM