I'm working on a simple lottery number checker using JavaScript for my website. The user enters three numbers through a form, and I have three winning numbers stored in an array. I want to check if the user's numbers match the winning numbers, regardless of the order.
Here’s my current setup:
function checkWin() {
const winningNumbers = [3, 5, 8];
const userNumbers = [
parseInt(document.lotteryForm.input1.value),
parseInt(document.lotteryForm.input2.value),
parseInt(document.lotteryForm.input3.value),
];
// Need logic to compare both arrays in any order
if (/* arrays match, any order */) {
alert("Congratulations! You matched all the winning numbers!");
} else {
alert("Sorry, try again!");
}
}
How can I check if the userNumbers array contains all the same numbers as the winningNumbers array, in any order?
Is it better to use sort() and compare, or should I loop through and use .includes()?
What’s the safest and most efficient method?