[英]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
對象,並使用布爾值確定所有子數組元素是否為true
( every
回調和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.