使用 OR || 运算符合并多个 JavaScript 布尔数组
我们有这么一个布尔数组数组 −
const arr = [[true,false,false],[false,false,false],[false,false,true]];
我们需要编写一个函数,该函数通过使用 OR (||) 运算符合并各个子数组的对应元素,将此数组数组合并到一维数组中。
让我们编写此函数的代码。我们将使用 Array.prototype.reduce() 函数来实现此目的。
示例
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));输出
控制台中的输出将为 −
[ true, false, true ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP