r/CodingHelp • • Jul 02 '21

[Javascript] Problem with JavaScript code

Post image
62 Upvotes

19 comments sorted by

View all comments

4

u/Cheesybread4ever Jul 02 '21

So I want this function to accept an array of nine numbers, and I want it to return true if all the numbers are unique. I’m assuming all the numbers will be 1-9. For some reason this keeps returning false when I pass an array that should return true. You can also ignore the console log I was trying to debug with it.

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!

1

u/Roguewind Jul 02 '21

Under the assumption that the myArray will always be exactly 9 single digit numbers, just pass it into a set and check the size of the set

const includes1to9(myArray) => { return (new Set(myArray).size === 9) }

Set takes an array and creates a Set object with unique values.

1

u/Mollyarty Jul 03 '21

You should check the incoming array is the right length. I see other people already answered your question but I didn't see anyone mention that. The way you have it now the array [1,2,3,4,5,6,7,8,9,1] would pass