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
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
Share Improve this question asked Jul 26, 2016 at 2:56 user4143172user4143172 1-
3
[...myArray.entries()].filter(([, v]) => v).map(([i]) => i);
– zerkms Commented Jul 26, 2016 at 3:04
3 Answers
Reset to default 6The 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./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;
}, []);