简体   繁体   中英

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. 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?

Thanks

The following is the first way that came to mind using vanilla 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.

Note that the map function (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===true ? i : -1 .

I guess the Lodash equivalent of that would be as follows (edit: thanks to zerkms for much improved syntax):

 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;
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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