简体   繁体   English

lodash,获取匹配元素的索引?

[英]lodash, get matched element's index?

Here is my case 这是我的情况

var myArray = [undefined, true, false, true];

I want to get the items' index, which value is true. 我想获取项目的索引,该索引值为true。 With above array, the result should be 使用上面的数组,结果应该是

[1, 3]

as the 2nd and 4th item equal true. 因为第二项和第四项相等。 How can I find the matched items' index with lodash? 如何使用lodash查找匹配项的索引?

Thanks 谢谢

The following is the first way that came to mind using vanilla JS: 以下是使用香草JS想到的第一种方法:

 var myArray = [undefined, true, false, true]; var result = myArray.map((v,i) => v ? i : -1).filter(v => v > -1); console.log(result); 

Or if you don't want to use arrow functions: 或者,如果您不想使用箭头功能:

var result = myArray.map(function(v,i) { return v ? i : -1; })
                    .filter(function(v) { return v > -1; });

That is, first map the original array to output the index of true elements and -1 for other elements, then filter that result to only keep the ones that aren't -1. 也就是说,首先映射原始数组以输出true元素的索引,其他元素的索引为-1,然后过滤结果以仅保留非-1的索引。

Note that the map function (v,i) => v ? i : -1 注意,映射函数(v,i) => v ? i : -1 (v,i) => v ? i : -1 is testing for truthy elements - if you need only elements that are the boolean true then use (v,i) => v===true ? i : -1 (v,i) => v ? i : -1正在测试真实元素-如果仅需要布尔true元素,则使用(v,i) => v===true ? i : -1 (v,i) => v===true ? i : -1 . (v,i) => v===true ? i : -1

I guess the Lodash equivalent of that would be as follows (edit: thanks to zerkms for much improved syntax): 我想Lodash的等效项如下(编辑:感谢zerkms改进了语法):

 var myArray = [undefined, true, false, true]; var result = _(myArray).map((v,i) => v ? i : -1).filter(v => v > -1).value(); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.js"></script> 

Another possibility: 另一种可能性:

// lodash 

x = _(myArray).map(Array).filter(0).map(1).value()

// vanilla

x = myArray.map(Array).filter(a => a[0]).map(a => a[1])
// lodash
var myArray = [undefined, true, false, true];
var indexes = _.reduce(myArray, (result, val, index) => {
    if (val) {
        result.push(index);
    }
    return result;
}, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM