I have an event-listener that adds a new item to an array every time I click an image. How can I check if the item newly-added to the array matches an item in the other array?
let a = ['a', 'b', 'c', 'd']
let b = []
grid.addEventListner('click', (e) =>{
let clicked = e.target
b.push(clicked)
// Here is where I want to check if the variable "clicked"
// which is pushed in to the b array matches
// the value on the same position in the a array. So for
// every click if its right I add a // green class and if
// its not I add a red class and finish the possibility
// to play.
})
Hope I was able to explain the problem :)
CodePudding user response:
If I understand correctly you want to check if the new item in b is equal to the item at the same position in a. You can this like so:
if (a[b.length - 1] === clicked) {
//set green
} else {
//set red
}
You can replace clicked
with b[b.length - 1]
if, when you are checking, clicked is out of scope.
If you are wanting to see if any item in a
matches the clicked
new item in b
you can use the array.find method.
if(a.find( el => el === clicked)) {
// set green
} else {
// set red
}
Based on where the comments in the code are, it appears you want this logic to run inside that function. Which is why I have added a simple if block here
CodePudding user response:
You can use Array.find
to check for the existence of an element in some Array
. An example:
const someArray = ['a', 'b', 'c', 'd'];
const newElem = 'a';
const newElem2 = 'hello';
console.log(someArray.find(elem => elem === newElem)
? `${newElem} exists!` : `${newElem} is new!`);
if (!someArray.find(elem => elem === newElem2)) {
someArray.push(newElem2);
}
console.log(JSON.stringify(someArray));
CodePudding user response:
You don't need another array to record the validity of the clicks; just a counter.
const buttonWrapper = document.getElementById('button_wrapper');
const a = ['a', 'b', 'c', 'd'].map(l => document.getElementById(`button_${l}`));
let counter = 0;
buttonWrapper.addEventListener('click', e => {
if (e.target.tagName === "BUTTON") {
if (e.target === a[counter]) {
buttonWrapper.classList.remove('red')
buttonWrapper.classList.add('green');
counter = (counter 1) % a.length;
} else {
buttonWrapper.classList.remove('green')
buttonWrapper.classList.add('red');
counter = 0;
}
}
});
#button_wrapper { display: table; padding: 10px; border: 4px solid #000; }
#button_wrapper.red { border-color: red; }
#button_wrapper.green { border-color: green; }
<div id="button_wrapper">
<button id="button_a">Button A</button>
<button id="button_b">Button B</button>
<button id="button_c">Button C</button>
<button id="button_d">Button D</button>
</div>