admin管理员组文章数量:1355594
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;
}, []);
本文标签: javascriptLoDashget matched element39s indexStack Overflow
版权声明:本文标题:javascript - lodash, get matched element's index? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744037296a2580011.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论