JavaScript merge multiple Boolean arrays with the OR || operator

JavascriptWeb DevelopmentObject Oriented Programming

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 ]
raja
Published on 26-Aug-2020 13:17:23
Advertisements