neaumusic neaumusic - 5 months ago 24
Javascript Question

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

RJM RJM
Answer

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);

See this Fiddle: https://jsfiddle.net/o1gLr115/

Comments