Javascript-在布尔数组中获取真值的索引 [英] Javascript - Get indices of true values in a boolean array

查看:455
本文介绍了Javascript-在布尔数组中获取真值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个具有以下值的数组-

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:

const arr = [true, true, false, false, false, true, false]
const indices = arr.reduce(
  (out, bool, index) => bool ? out.concat(index) : out, 
  []
)
console.log(indices)

您首先将一个空数组 [] 作为 initialValue 传递给 .reduce(),然后使用 .concat() index .

You start by passing an empty array [] as the initialValue to .reduce() and use a ternary ? operator to determine whether to .concat() the index or not.

或者,您可以使用更新的 .flatMap() 方法:

Alternatively, you can use the more recent .flatMap() method:

const arr = [true, true, false, false, false, true, false]
const indices = arr.flatMap((bool, index) => bool ? index : [])
console.log(indices)

如果您的浏览器尚不支持它,您将得到 Uncaught TypeError:arr.flatMap不是一个函数.在这种情况下,您可以从此处使用我的polyfill定义.

If your browser does not yet support it, you'll get an Uncaught TypeError: arr.flatMap is not a function. In that case, you can use my polyfill definition from here.

这篇关于Javascript-在布尔数组中获取真值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆