简体   繁体   English

从数组中获取所有元素均为真的子数组的所有索引

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

This is an example of an array I can have: 这是我可以拥有的数组的示例:

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

How can I check if all the values in a sub-array are true and then get all indexes of sub-arrays which pass the check? 如何检查子数组中的所有值是否都为true ,然后获取通过检查的子数组的所有索引?

Use map to create objects that hold the index and a boolean whether all sub-array elements are true (with every and Boolean as the callback), filter to select only those where all elements are true , then another map to get only the indexes. 使用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)); 

You could reduce the outer array by checking the inner array and take the index or nothing. 您可以通过检查内部数组来缩小外部数组,并获取索引或不进行任何操作。

 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