Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull array values associated with bitmask

I have a simple bitmask, 3 ("011" in base 2) which denotes that I should extract array[0] and array[1] but not array[2]

What is an efficient way to do this?

Ultimately, I'm generating a new array with values that passed a .filter

Something like this:

var bitmask = 37, // "100101"
    array = ["a", "b", "c", "d", "e", "f"];

var array2 = array.filter((value, index) => {
    // do something with bitmask and index to return true
});

// array2 should be ["a", "c", "f"];
like image 337
neaumusic Avatar asked Dec 08 '22 22:12

neaumusic


1 Answers

Expanding on your original example you can do this:

var bitmask = 37, // "100101"
    array = ["a", "b", "c", "d", "e", "f"];

var array2 = array.filter((value, index) => {
    // do something with bitmask and index to return true
    return bitmask & (1 << index);
});

// array2 should be ["a", "c", "f"];
console.log(array2);
like image 183
RJM Avatar answered Dec 10 '22 11:12

RJM