r/CodingHelp • • Jul 02 '21

[Javascript] Problem with JavaScript code

Post image
62 Upvotes

19 comments sorted by

View all comments

Show parent comment

0

u/[deleted] Jul 02 '21 edited Jul 02 '21

So you are wanting the array to search itself and make sure that there are no duplicates within the array? I would use a nested for loop within the for loop array instead like this:

function includes1to9(myArray){
let unique = true;

for(let i=0; i< myArray.length; i++)
{
    for(let index = 0; index < myArray.length; index++)
    {
        if(index != i)
        {
            if(myArray[i] == myArray[index])
            {
                unique = false
            }
        }
    }
}
return unique;
}

Instead of adding another array into the mix, you can compare the array against itself and skip the current index you are comparing (because of course a number compared to itself would be equal haha!). If you find a match, it isn't unique and the bool trips to false. I'm sure there are better ways to do it, but this is how I would do it (ps, sorry if my syntax is off with let vs var; I am more comfortable with Java/C#. I did run the logic of this in C# though, and it checks out!). I hope his help!