Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that checks whether all characters in a string are equal javascript - Homework Warning

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) 
like image 535
EKR Avatar asked Dec 11 '22 13:12

EKR


2 Answers

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
like image 110
Jecoms Avatar answered May 13 '23 16:05

Jecoms


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.

like image 29
Barmar Avatar answered May 13 '23 16:05

Barmar