Merging boolean array with AND operator - JavaScript

Let's say, we have an array of arrays of boolean like this ?

const arr = [[true,false,false],[false,false,false],[false,false,true]];

We are required to write a function that merges this array of arrays into a one-dimensional array by combining the corresponding elements of each subarray using the AND (&&) operator.

Let's write the code for this function. We will be using Array.prototype.reduce() function to achieve this.

Example

Following is the code ?

const arr = [[true,false,false],[false,false,false],[false,false,true]];

const andMerge = (arr = []) => {
    return arr.reduce((acc, val) => {
        val.forEach((bool, ind) => {
            acc[ind] = acc[ind] && bool || false;
        });
        return acc;
    }, []);
};

console.log(andMerge(arr));

Output

This will produce the following output in console ?

[ false, false, false ]

How It Works

The function works by:

  • Using reduce() to accumulate results starting with an empty array
  • For each subarray, iterating through its boolean values with forEach()
  • Applying the AND operation between the accumulator value and current boolean
  • Using || false to handle the first iteration when acc[ind] is undefined

Alternative Approach Using map()

Here's another way to achieve the same result:

const arr = [[true,false,false],[false,false,false],[false,false,true]];

const andMergeAlternative = (arr = []) => {
    const length = arr[0] ? arr[0].length : 0;
    return Array.from({length}, (_, index) => 
        arr.every(subArr => subArr[index])
    );
};

console.log(andMergeAlternative(arr));
[ false, false, false ]

Conclusion

Both approaches merge boolean arrays using the AND operator effectively. The reduce() method provides more control, while every() offers cleaner logic for AND operations across corresponding positions.

Updated on: 2026-03-15T23:18:59+05:30

818 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements