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 is testing for truthy elements - if you need only elements that are the boolean true then use (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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With