-2

What I'm trying to do is take my Python code and turn it into JavaScript, yet I cannot figure out why it runs differently in JavaScript. What am I missing?

The code is intended to take an array of values with 1's and 0's and return an array summing the 1 values as such.

[1,1,0,1] => [2,1]

[0,0,1,1,1] => [3]

[0,0,0] => []

[1,1,0,0] => [2]

Python code that works (unless I'm horribly mistaken)

def encode(arr):
    arr2=[]
    num = 0
    for i in arr:
        if i==1:
            num=num+1
        elif i==0 and num ==0:
            pass
        else:
            arr2.append(num)
            num=0
    if num>0:
        arr2.append(num)
    return arr2

JavaScript that doesn't work

function  encode(arr) {
    var arr2=[];
    var num = 0;
    for (i in arr){
        if (i==1) {
            num++;
        } else if (i == 0 && num == 0) {
            // pass 
        } else {
            arr2.push(num);
            num=0;
        }
    }

    if (num>0) {
        arr2.push(num)   
    }

    return arr2;
}
CRice
  • 29,968
  • 4
  • 57
  • 70
Sam Dotson
  • 35
  • 1
  • 6

1 Answers1

1

Instead of

for (i in arr) { ... }

you need to write

for (let i of arr) { ... }

This is because for ... in iterates the enumerable properties, i.e. the array indices. But you want to iterate the array values.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in and also Why is using "for...in" with array iteration a bad idea?

le_m
  • 19,302
  • 9
  • 64
  • 74