JavaScript merge multiple Boolean arrays with the OR || operator


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 OR (||) operator.

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

Example

const arr = [[true,false,false],[false,false,false],[false,false,true]];
const orMerge = arr => {
   return arr.reduce((acc, val) => {
      val.forEach((bool, ind) => acc[ind] = acc[ind] || bool);
      return acc;
   }, []);
};
console.log(orMerge(arr));

Output

The output in the console will be −

[ true, false, true ]

Updated on: 26-Aug-2020

359 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements