Merging boolean array with AND operator - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ]
raja
Published on 18-Sep-2020 12:36:07
Advertisements