[英]Javascript - Get indices of true values in a boolean array
Let's say I have an array with the following values -假设我有一个具有以下值的数组 -
var arr = [true, true, false, false, false, true, false];
I'm looking for logic which will give me the following output -我正在寻找可以给我以下输出的逻辑 -
[0,1,5]
You can use .reduce()
to do this in one pass:您可以使用.reduce()
一次性完成此操作:
const arr = [true, true, false, false, false, true, false] const indices = arr.reduce( (out, bool, index) => bool ? out.concat(index) : out, [] ) console.log(indices)
You start by passing an empty array []
as the initialValue
to .reduce()
and use a ternary ?
您首先将一个空数组[]
作为initialValue
传递给.reduce()
并使用三元?
operator to determine whether to .concat()
the index
or not. 运算符来确定是否.concat()
index
。
Alternatively, you can use the more recent .flatMap()
method:或者,您可以使用更新的.flatMap()
方法:
const arr = [true, true, false, false, false, true, false] const indices = arr.flatMap((bool, index) => bool ? index : []) console.log(indices)
If your browser does not yet support it, you'll get an Uncaught TypeError: arr.flatMap is not a function
.如果你的浏览器还不支持它,你会得到一个Uncaught TypeError: arr.flatMap is not a function
。 In that case, you can use my polyfill definition from here .在这种情况下,您可以从这里使用我的 polyfill 定义。
You could map the indices or for falsy values -1
and then filter all indices which are not -1
.您可以映射索引或虚假值-1
,然后过滤所有不是-1
索引。
var array = [true, true, false, false, false, true, false], result = array .map((b, i) => b ? i : -1) .filter(i => i !== -1); console.log(result);
A potentially more elegant solution is:一个可能更优雅的解决方案是:
[...arr.keys()].filter(i => arr[i])
or alternatively或者
[...arr.entries()].filter(([, v]) => v).map(([i]) => i)
You can simply use a loop and check the boolean value true
in your if
condition:您可以简单地使用循环并检查if
条件中的布尔值true
:
var arr = [true, true, false, false, false, true, false]; var indexArray = []; arr.forEach((val, index) => { if(val){ indexArray.push(index); } }); console.log(indexArray);
try this尝试这个
var arr = [true, true, false, false, false, true, false]; var indexArray = []; arr.forEach(function(value, index) { if (value) { indexArray.push(index); } }) console.log(indexArray);
Different solution based on logic itself and not JS paradigms基于逻辑本身而非 JS 范式的不同解决方案
let newArr = [];
for (let i = 0 ; i<indexArray.length;i++){
if (indexArray[i]) newArr.push(i)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.