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>