Get all index value of 1 from binary "01000111"

- 1 answer

Ad

I tried to get all the indexes from the binary like "01000111" so it should return an array [1,2,3,7];

I have tried this to get the index :

var getIndex1 = function(binary){
    var str = binary.toString();
    var indices = [];
    for(var i=0; i<str.length;i++) {
        if (str[i] == "1"){
          indices.push(i);
        } 
    }
    return indices;
  };

when I tried to get the index using that function I got this :

return getIndex1("01000111"); // it returns [0,2,3,4]

I tried the same function to get all indexes of "s" from scisorss and it works fine. Anyone had this kind of problem? what I'm missing here? please help, and thanks.

Ad

Answer

Ad

Try this plunker.

The code you provided is returning [1,5,6,7]. Which is the expected behavior.

With the string "01000111", indexes 1,5,6 and 7 have a value of 1

If you want to go right to left, you should change your function to:

var getIndex1 = function(binary){
    var str = binary.toString();
    var indices = [];
    for(var i=str.length; i>0; i--) {
        if (str[i] == "1"){
          indices.push(str.length - i - 1);
        } 
    }
    return indices;
  };
Ad
source: stackoverflow.com
Ad