1

I have an array like this:

parent = [
    {'id':'id_1','level':'1-1','children':['id':'id_1','level':'1-1-0','children':[........]},
    {'id':'id_2','level':'2-2','children':['id':'id_1','level':'2-1-0','children':[........]}
]

How can I get the parent array index that match the condition of child array object

For example:

If (level == '2-1-0') 

Output: 1

Expected Behaviour:

It should return 1 because level 2-1-0 present in 1'st index of parent array

Note: I tried like below

var index = parent .findIndex(data => data.level== result.level);

It will not check child array object

3
  • 1
    The array stored in the parent variable is syntactically invalid: can you update your question? Also, is there arbitrary level of nesting for children? Commented Jan 6, 2022 at 11:02
  • You're right, this will not check the children in the object. You will have to go through each child array and check it against your result.level. Commented Jan 6, 2022 at 11:02
  • Your children array is not a va;id array. Also is its just to find the matching level from the child objects in the array? Asking this specifically because you children array already have an another children node. Commented Jan 6, 2022 at 11:02

5 Answers 5

3

Your provided array is wrong, but I think that you need something like this:

const parent = [
    {'id':'id_1','level':'1-1','children':[{'id':'id_1','level':'1-1-0'}]},
    {'id':'id_2','level':'2-2','children':[{'id':'id_1','level':'2-1-0'}]}
]

const index = parent.findIndex(p => p.children.find(c => c.level === '2-1-0') !== undefined);

console.log(index);

In the place of '2-1-0' you should put the index, that you want to check.

Sign up to request clarification or add additional context in comments.

2 Comments

This solution doesn't work for different depths (eg, level = '1-3-4-5')
Ok, the question not say about depths, but if encapsulate the logic into a function, we can use a recursive call to do this.
1

It's a recursive problem, which can blow the stack for big arrays.

The script traverses the tree depth first and can be optimized to detect the requested level depth and only check that level, increasing the performance.

var weirdProblem = level => (carry, current, idx) => {
  // bail if already found 
  if (carry > -1) {
    return carry;
  }

  // check current item's children and return current idx if matching
  if (current.children.some(child => child.level === level)) {
    return idx;
  }

  // traverse current item's children
  return current.children.reduce(weirdProblem(level), -1);
};

var index = parent.reduce(weirdProblem('2-1-0'), -1);

did not test the script.

Comments

0

You need recursion

const findItemNested = (arr, level, nestingKey) => (
  arr.reduce((a, item, index) => {
    if (a) return a;
    if (item.level === level) return index;
    if (item[nestingKey]) return findItemNested(item[nestingKey], level, nestingKey)
  }, null)
);
const testArr = [
      {
        'id':'id_1',
       'level':'1-1',
       'children':[
         {'id':'id_1'},
         {'level':'1-1-0'},
         {'children':[]}
       ]
      },
      {'id':'id_2','level':'2-2','children':[{'id':'id_1'},{'level':'2-1-0'},{'children':[]}]}
  ];

const res = findItemNested(testArr, '2-1-0', "children");

console.log(res) //  1

1 Comment

It's working 75% of my requirment, I made some update in this code .
0

Your parent array is malformed, I guess it should be a nested structure.

Since children may also contains more children, you will need recursion for a deep search.

const parent = [
    {"id": "id_1", "level": "1-1", "children": [{"id": "id_1", "level": "1-1-0", "children": []}]},
    {"id": "id_2", "level": "2-2", "children": [{"id": "id_1", "level": "2-1-0", "children": []}]}
];

function levelIndex(children, level) {
    return children.findIndex(child => child.level == level || levelIndex(child.children, level) >= 0);
}
    
const index = levelIndex(parent, "2-1-0");
console.log("Found index:", index)

Comments

0

in .TS file:-

const parent = [
    {'id':'id_1',
     'level':'1-1',
     'children':[{'id':'id_1',
                  'level':'1-1-0'}]},
                 {'id':'id_2',
                  'level':'2-2',
                  'children':[{'id':'id_1',
                               'level':'2-1-0'}]}
]

const index = parent.filter(x => x.children.find(x => x.level === '2-1-0') !== undefined);

console.log(index);

Give this a try. I think it will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.