Search code examples
javascriptfor-loopfor-of-loop

Why is the for of loop inside the functions body not giving me the expected output that the traditional for loop is doing?


Why is the for of loop inside the functions body not giving me the expected output that the traditional for loop is doing? Seems like the el in the for of loop is not the same as iterable[i] in the for loop?

var uniqueInOrder = function(iterable){
     let unique = [];
     for(let el of iterable){
         let cur = el;
         let next = el + 1;
         if(cur !== next){
             unique.push(cur)
         }
     }
     return unique;
}
uniqueInOrder('AAAABBBCCDAABBB')  // unexpected output

// Returns expected output
var uniqueInOrder = function(iterable){
     let unique = [];
     for(var i = 0; i < iterable.length; i++){
         let cur = iterable[i];
         let next = iterable[i + 1];
         if(cur !== next){
             unique.push(cur)
         }
     }
     return unique;
}
uniqueInOrder('AAAABBBCCDAABBB') // ----> ["A", "B", "C", "D", "A", "B"]

Solution

  • Like @Sxribe describe, the for/of loop is fundamentally different, and you can't use el+1 to get the next value.

    A functionnal way to get the same result with both loops is :

    var uniqueInOrder = function(iterable){
         let unique = [];
         let prev = ''
         for(let el of iterable){
             let cur = el;
             if(cur !== prev){
                prev = el
                 unique.push(prev)
             }
         }
         return unique;
    }
    console.log(uniqueInOrder('AAAABBBCCDAABBB'))
    
    // Returns expected output
    var uniqueInOrder = function(iterable){
         let unique = [];
         for(var i = 0; i < iterable.length; i++){
             let cur = iterable[i];
             let next = iterable[i + 1];
             if(cur !== next){
                 unique.push(cur)
             }
         }
         return unique;
    }
    console.log(uniqueInOrder('AAAABBBCCDAABBB'))
    

    In this example instead of checking the current value against the next one, we check the current value against the previous one.