I'm with an existential doubt.
I have a function, which must return true in case each element of an array is equal to the other.
I have an arrangement with five elements that constantly change, and every time a new element is set, the function already said is executed and it checks if all the elements are equal.
Up here everything is fine. The problem is that I made a set of conditional (copypaste), but it is a horrible way to write a code, so I turn to these forums to see what solutions they offer.
A functional demonstration similar to my code.
let contador = ["juan", "juan", "juan", "juan", "juan"]
function bantrue() {
if (contador[0] == contador[1]) {
if (contador[1] == contador[2]) {
if (contador[2] == contador[3]) {
if (contador[3] == contador[4]) {
return true
}
}
}
}
}
if (bantrue() === true){
document.write("bantrue() es true.");
}
//PERO SI ES FALSO
let contador2 = ["juan", "Manuel", "juan", "juan", "juan"]
function bantrue2() {
if (contador2[0] == contador2[1]) {
if (contador2[1] == contador2[2]) {
if (contador2[2] == contador2[3]) {
if (contador2[3] == contador2[4]) {
return true
}
}
}
}
}
if (bantrue2() === true){
document.write("true");
} else {
document.write(" ------- bantrue2() es false.");
}
As you can see, the first function returns true because the array has all "john", but the second array has a "manuel", so the conditionals stop.
What if I want to increase the amount of items that counter [] stores? Do I have to copy and paste the ifs five times more? I do not see it practical.
I would greatly appreciate other solutions to perform this check. From already thank you very much.