使用 AND 运算符合并布尔数组 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/15 9:48:17

假设我们有一个像这样的布尔数组数组 −

const arr = [[true,false,false],[false,false,false],[false,false,true]];

我们需要编写一个函数,通过使用 AND (&&) 运算符组合每个子数组的相应元素,将此数组合并为一维数组。

让我们为该函数编写代码。我们将使用 Array.prototype.reduce() 函数来实现这一点。

示例

以下是代码 −

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));

输出

这将在控制台中产生以下输出 −

[ false, false, false ]

相关文章


有用资源