[英]Find index of array of array object
I need to find the index of an array of array object where it is true.我需要找到数组对象数组的索引,它是真的。 My array:
我的阵列:
[
[
{id: 1, status: false},
{id: 2, status: true}
],
[
{id: 13, status: false},
{id: 14, status: false}
],
[
{id: 18, status: true},
{id: 19, status: false}
]
]
In the case above I should expect index 0 and 2 to be returned.在上述情况下,我应该期望返回索引 0 和 2。
Use reduce
to get indices of the elements where some
items fulfill the condition:使用
reduce
获取some
项目满足条件的元素的索引:
input.reduce((acc, arr, i) => (
arr.some(obj => obj.status) && acc.push(i)
, acc), [])
const input = [[{"id":1,"status":false},{"id":2,"status":true}],[{"id":13,"status":false},{"id":14,"status":false}],[{"id":18,"status":true},{"id":19,"status":false}]]; const result = input.reduce((acc, arr, i) => ( arr.some(obj => obj.status) && acc.push(i) , acc), []); console.log(result);
There are two steps in the solution of the problem.问题的解决有两个步骤。
const data = [ [ { id: 1, status: false }, { id: 2, status: true }, ], [ { id: 13, status: false }, { id: 14, status: false }, ], [ { id: 18, status: true }, { id: 19, status: false }, ], ]; let ret = []; data.forEach((x, i) => { if (x.some((y) => y.status)) ret.push(i); }); console.log(ret); ret = []; data.forEach((x, i) => { if (x.filter((y) => y.status).length > 0) ret.push(i); }); console.log(ret);
I have used both some and filter methods to check the condition and for array traversese I have used array forEach method.我使用了some和filter方法来检查条件,对于数组遍历,我使用了 array forEach方法。
Basically same solution as from marzelin, but more readable in my opinion.与 marzelin 的解决方案基本相同,但在我看来更具可读性。 The comma operator in the callback return value can be quite confusing.
回调返回值中的逗号运算符可能会非常混乱。
const data = [ [ {id: 1, status: false}, {id: 2, status: true} ], [ {id: 13, status: false}, {id: 14, status: false} ], [ {id: 18, status: true}, {id: 19, status: false} ] ] //pV=previous value, cV=current value, cI=current index const result = data.reduce(function (pV, cV, cI) { if (cV.some(function (obj) { return obj.status })) { pV.push(cI); } return pV; },[]); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.