简体   繁体   English

查找数组对象数组的索引

[英]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.问题的解决有两个步骤。

  • First traverse the array首先遍历数组
  • Second check the condition.其次检查条件。 You can check the condition using two array methods.您可以使用两种数组方法检查条件。
    • some: Checks if any of the elements in an array pass a test and returns true or false based on the test. some:检查数组中的任何元素是否通过测试并根据测试返回真或假。
    • filter: Creates an array based on condition and that's the reason I checked array length in the following code. filter:根据条件创建一个数组,这就是我在以下代码中检查数组长度的原因。

 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.我使用了somefilter方法来检查条件,对于数组遍历,我使用了 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.

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