Haleem ul Hassan Haleem ul Hassan - 1 year ago 77
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

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
or not (no letters should be repeated). With nested
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.


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download