Home > Mobile >  JavaScript : Optimal solution to filtered out the objects from an array based on the n-level nested
JavaScript : Optimal solution to filtered out the objects from an array based on the n-level nested

Time:11-12

Requirement: Is there any optimal or easy way to filtered out the objects from an array which contains a specific property based on its value without recursion.

Problem statement: We can achieve this requirement with the help of recursion but as data set (array of objects) is very large and each object contains n number of nested objects, Recursion approach is causing performance issue.

Here is the sample mock data:

[{
  children: [{
    children: [{
      children: [],
      isWorking: 'yes'
    }]
  }]
}, {
  children: [],
  isWorking: 'no'
}, {
  children: [{
    children: [{
      children: [],
      isWorking: 'no'
    }]
  }]
}, {
  children: [{
    children: [],
    isWorking: 'yes'
  }]
}, ...]
  • I want to filter out the root objects from an array which contains nested isWorking property with the value as yes.
  • isWorking property will only available for the objects which does not contains children. i.e. children: []

As I said earlier, I am able to achieve this by recursion but looking for a optimal solution which will not impact the performance.

This is what I tried (Working solution):

const parent = [{
  children: [{
    children: [{
      children: [],
      isWorking: 'yes'
    }]
  }]
}, {
  children: [],
  isWorking: 'no'
}, {
  children: [{
    children: [{
      children: [],
      isWorking: 'no'
    }]
  }]
}, {
  children: [{
    children: [],
    isWorking: 'yes'
  }]
}];

const isWorkingFlagArr = [];

function checkForOccupation(arr) {
  arr.forEach(obj => {
    (!obj.children.length) ? isWorkingFlagArr.push(obj.isWorking === 'yes') : checkForOccupation(obj.children)
  })
}

checkForOccupation(parent);

const res = parent.filter((obj, index) => isWorkingFlagArr[index]);

console.log(res);

CodePudding user response:

The following puts each recursive call on a new microtask, thereby avoiding blowing the stack.

This code runs the same algorithm as yours but ensures that recursive calls are made asynchronously on new microtasks here.

In the following code

  • Related