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);
}
CodePudding user response:
First, let me prove that findIndex
works like you expect:
console.log([2, 1, 3, 4, 5, 6, 1].findIndex(item => item === 1))
Now, let's see what happens if you repeatedly apply findIndex
while replacing your items:
let foo = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
for (let element of foo) {
foo[foo.findIndex(item => item === element)] = "*";
}
console.log(foo);
So, how do you avoid overriding items that were overriden:
let foo = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2];
let replacedItems = [];
for (let element of foo) {
if (replacedItems.indexOf(element) < 0) {
replacedItems.push(element);
foo[foo.findIndex(item => item === element)] = "*";
}
}
console.log(foo);
So, what is the problem that you have? The problem is that you replace your item with * and then search for the same item in the same array when it was already replaced at its former first index, so it's current first index is at a higher position, particularly the last one in your example.
What was the solution? We keep track of the item whose index was already found and avoid doing similar replaces.