Basically the idea is that my code chooses a random element from an array. That element is the arr[i].answer
and is placed at the end of that array. Then i want to make the first occurrence of that answer as an *
. I used the findIndex method as i thought that the first occurrence of my answer will become the *
however both first occurrence and the last element have become an asterix.
Here is the code
arr.forEach(element => {
arr[i].answer = arr[i].sequence[rndElement];
arr[i].sequence[arr[i].sequence.length - 1] = arr[i].answer;
function isFirst(element, index, array) {
return element === arr[i].answer;
}
let index = arr[i].sequence.findIndex(isFirst);
arr[i].sequence[index] = "*";
});
Above is the necessary code, below is all the code for reference
const arr = [];
const input = document.getElementById('answer').value;
const rndElement = Math.floor(Math.random() * 6);
function displaySeq() {
var i = 0;
while (arr.length < 21) {
const rndInt = Math.floor(Math.random() * 50);
const iterator = Math.floor(Math.random() * (8 - 3 + 1)) + 3;
arr[i] = {
sequence: [rndInt],
answer: 7,
guess: []
};
let j = iterator;
while (arr[i].sequence.length < 7) {
arr[i].sequence.push(rndInt + j);
j+=iterator;
}
arr.forEach(element => {
arr[i].answer = arr[i].sequence[rndElement];
arr[i].sequence[arr[i].sequence.length - 1] = arr[i].answer;
function isFirst(element, index, array) {
return element === arr[i].answer;
}
let index = arr[i].sequence.findIndex(isFirst);
arr[i].sequence[index] = "*";
});
i++;
}
console.log(arr);
}