Haleem ul Hassan Haleem ul Hassan - 4 months ago 23
Javascript Question

How to do Nested For Loops in Functional Style

I'm in the process of learning functional programming, and completely getting rid of

for
loops has been a challenge sometimes, because they provide so much control and freedom. Below is an example of checking if a string is an
isogram
or not (no letters should be repeated). With nested
for
loops, it became an easy solution. Is there a way to do this the functional way with any high order functions or anything else? Any suggestion would be a huge help.

Code:

function isIsogram(string) {
let array = string.split('');
let condition = true;
for (let i = 0; i < string.length; i++) { //first loop picks character
for (j = i + 1; j < string.length; j++) { //second loop compares it rest
if (array[i].toLowerCase() == array[j].toLowerCase())
condition = false; //if repeat, the condition false
}
return condition;
}
}

Answer

You can use every or some together with a suitable string function:

function isIsogram(string) {
    string = string.toLowerCase(); // case insensitive
    return string.split('').every(function(character, index) {
        return !string.includes(character, index+1);
    });
}

Instead of includes you might also have utilised indexOf.