使用 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 ]

更新於: 2020-08-26

398 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.