AND product of arrays in JavaScript

We have an array of arrays of boolean values 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

The code for this will be:

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

The output in the console will be:

[ false, false, false ]

How It Works

The function works by:

  1. Using reduce() to iterate through each subarray
  2. For each element at index ind, applying the AND operation with the accumulator value
  3. The expression acc[ind] && bool || false ensures proper initialization 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 andMergeMap = (arr = []) => {
    if (arr.length === 0) return [];
    
    return arr[0].map((_, index) => 
        arr.every(subArray => subArray[index])
    );
};

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

Conclusion

Both approaches effectively merge boolean arrays using the AND operation. The reduce method builds the result incrementally, while the map approach checks if all elements at each position are true.

Updated on: 2026-03-15T23:19:00+05:30

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements