簡體   English   中英

從數組中獲取所有元素均為真的子數組的所有索引

[英]From an array, get all indexes of sub-arrays where all elements are true

這是我可以擁有的數組的示例:

let testArray = [
  [true, true, false],
  [false, true, false],
  [true, true, true],
  [false, true, false],
  [true, true, true]
]

如何檢查子數組中的所有值是否都為true ,然后獲取通過檢查的子數組的所有索引?

使用map創建包含index對象,並使用布爾值確定所有子數組元素是否為trueevery回調和Boolean作為回調), filter以僅選擇所有元素為true那些,然后使用另一個map僅獲取索引。

 let testArray = [ [true, true, false], [false, true, false], [true, true, true], [false, true, false], [true, true, true] ]; console.log(testArray .map((subArray, index) => ({ index, allTrue: subArray.every(Boolean) })) .filter((entry) => entry.allTrue) .map((entry) => entry.index)); 

您可以通過檢查內部數組來縮小外部數組,並獲取索引或不進行任何操作。

 var array = [[true, true, false], [false, true, false], [true, true, true], [false, true, false]], allTrue = array.reduce((r, a, i) => r.concat(a.every(Boolean) ? i : []), []); console.log(allTrue); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM