Noud
Noud

Reputation: 55

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"]

Upvotes: 1

Views: 48

Answers (3)

Flubssen
Flubssen

Reputation: 65

As @Sxribe is saying, you get the element instead of the i count.

So you need to check if el exits in the array and push it to the array if it dosen't. So something like this would do it.

function uniqueInOrder (iterable){
   let unique = [];
   for(let el of iterable){
      let cur = el;
      if(unique.indexOf(el) === -1){
         unique.push(cur)
      }
   }
   return unique;
}

console.log(uniqueInOrder('AAAABBBCCDAABBB'));

Upvotes: 0

user3399
user3399

Reputation: 254

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.

Upvotes: 0

Sxribe
Sxribe

Reputation: 829

Your issue is in your first function.

In JavaScript, element in for (let element of inerable) {} is not the same as i in your traditional for loop. When you write let next = el +, you are adding 1 to an element, not a number (so, in this case you are doing 'A' + 1, like @Seblor said).

tl;dr el is not the same as i

Upvotes: 3

Related Questions