79684670

Date: 2025-06-30 11:14:56
Score: 0.5
Natty:
Report link

How can I check if the userNumbers array contains all the same numbers as the winningNumbers array, in any order?

sort, convert to string,compare

function checkWin() {
    const winningNumbers = [3, 5, 8];
    const userNumbers = [
        parseInt(document.lotteryForm.input1.value),
        parseInt(document.lotteryForm.input2.value),
        parseInt(document.lotteryForm.input3.value),
    ];
    //console.dir(winningNumbers.sort().toString());
    //console.dir(userNumbers.sort().toString());

    // Need logic to compare both arrays in any order
    if (winningNumbers.sort().toString()==userNumbers.sort().toString()) {
        alert("Congratulations! You matched all the winning numbers!");
    } else {
        alert("Sorry, try again!");
    }
}
<form name="lotteryForm">
<input type="text" name="input1" value="3">
<input type="text" name="input2" value="5">
<input type="text" name="input3" value="8">
</form>
<hr>
<button onclick="checkWin()">test</button>

Is it better to use sort() and compare, or should I loop through and use .includes()?

sort and compare is the best option or you'll need nested loops ( .includes() will loop the whole array so you have nested loop)

What’s the cleanest and most efficient method?

i think: sort both, start the loop for i<ceil(l/2) and compare a[i]==b[i] && a[l-i]==b[l-i] exit on first false

function checkWin() {
    const winningNumbers = [3, 5, 8];
    const userNumbers = [
        parseInt(document.lotteryForm.input1.value),
        parseInt(document.lotteryForm.input2.value),
        parseInt(document.lotteryForm.input3.value),
    ];
    //console.dir(winningNumbers.sort().toString());
    //console.dir(userNumbers.sort().toString());
    let a=winningNumbers.sort();
    let b=userNumbers.sort();
    let res=a.length==b.length;
    if(res){
      for(i=0;(i<Math.ceil(a.length/2) && res);i++){
        res=(a[i]==b[i] && a[a.length-i]==b[a.length-i]);
      }
    }

    // Need logic to compare both arrays in any order
    if (res) {
        alert("Congratulations! You matched all the winning numbers!");
    } else {
        alert("Sorry, try again!");
    }
}
<form name="lotteryForm">
<input type="text" name="input1" value="3">
<input type="text" name="input2" value="5">
<input type="text" name="input3" value="8">
</form>
<hr>
<button onclick="checkWin()">test</button>

Reasons:
  • Blacklisted phrase (0.5): How can I
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): How can I
  • Low reputation (0.5):
Posted by: emilianoc