I found a solution to this homework question, but I dont feel its the most efficient way to tackle the problem. Interested in other solutions I should explore.
Question: Write a function named allEqual that returns true if every character in the string is the same
Example:
If you pass "aaa" it should return true If you pass "aba" it should return false */
My Code
var stringAE = "aba";
function allEqual(string) {
var stringAENew = "";
for (var i = 0; i < string.length; i++) {
if (string[0] === string[i]) {
stringAENew += string[i];
console.log(stringAENew)
}
}
return stringAENew === string;
}
allEqual(stringAE)
Simple solution using .every()
.
function allEqual(input) {
return input.split('').every(char => char === input[0]);
}
console.log(allEqual('aba')); // false
console.log(allEqual('aaa')); // true
console.log(allEqual('')); // true
You can return false
immediately once you find a character that doesn't match the first character. If you make it through the whole loop, return true
because all the characters must have matched.
function allEqual(string) {
for (var i = 1; i < string.length; i++) {
if (string[i] != string[0]) {
return false;
}
}
return true;
}
You can also start your loop at i = 1
, since the first character is obviously equal to itself, so there's no need to test it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With