Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
|| falseto handle the first iteration whenacc[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.
Advertisements
