Home > Software design >  I want to set a "for" counter for each array in only one "for" declaration, rath
I want to set a "for" counter for each array in only one "for" declaration, rath

Time:08-30

// Declared Arrays

const aList3 = ["frog", "hippo", "snake", "owl", "sheep"];
const aList4 = ["eagle", "bee", "crab", "hippo", "iguana"];

// Declaring the Function

function isEqual(animals, animals2) {

// Declaring a Counter for Each Array

    for (let j = 0, k = 0; j < animals.length, k < animals2.length; j  , k  ) {

// Declaring the Condition

        if (animals[j] === animals2[k]) {
            return "You finded this common animals: "   animals[j];
        }
    }
    return "You didn't find any common animal";
}

// Calling the Function

const sameAnimal3 = isEqual(aList3, aList4);
console.log(sameAnimal3);

Some solution is use the same for counter, but for me doesn't work. I want it to work no matter of the index position or the length

for (let i = 0; i < animals.length; i  ) {
    if (animals[i] === animals2[i]) {
        return "You finded this common animals: "   animals[i];
    }
    return "You didn't find any common animal";
}

CodePudding user response:

This is possible by allowing both arrays to use the same for counter:

for (let i = 0; i < animals.length; i  ) {
    if (animals[i] === animals2[i]) {
        return "You finded this common animals: "   animals[i];
    }
    return "You didn't find any common animal";
}

But you have to be careful in a scenario where:

  1. The arrays have different lengths
  2. The common animal is not in the same index.

To properly solve this, use a dictionary to keep track of seen animals:

// Dictionary to keep track of seen animals.
const seen = {}

for (let i = 0; i < animals.length; i  ) {

    // Check both array's current index if animal is seen already.
    if(seen[animals[i]] || seen[animals2[i]]) {

        // If seen already, take which animal is found between the two array.
        const foundAnimal = seen[animals[i]] ? animals[i] : animals2[i]
        
        return "You finded this common animals: "   foundAnimal;
    } else {

        // If neither animals are seen before, add to the seen dictionary for future reference.
        seen[animals[i]] = true;
        seen[animals2[i]] = true;
    }
}

// You have not seen any animals twice.
return "You didn't find any common animal";
  • Related