complex filter with some method to filter out nested object data.

This is example of complex filter with some method to filter out nested object data.
 
let a = [{ name: 'hugh' }, { name: 'wyne' }, { name: 'tony' }];
let a1 = [{ name: 'john' }, { name: 'stark' }, { name: 'god' }];
let a2 = [{ name: 'tony' }, { name: 'stark' }, { name: 'wyne' }];

let b = [{ bname: 'bname'a: a }, { bname: 'bname'a: a1 }, { bname: 'bname'a: a2 }];

let r2 = b.filter(x => x.a.some(g => {
    console.log('some'g.name === 'hugh');
    return g.name === 'hugh'

}))

console.log(r2);
This very simple example that show how easily we search or filters items from a nested array object, there is an approach followed by this code example

Approach

1. We need a nested array object so we having 3 array variable's name are a, a1 and a2 and variable b that is holding other these 3 arrays to made a nested array object. You can see property a in array b.

2. We going to make use of two methods of array object these are array.filter and array.some.  array.filter take an expression to filter an array and return new array according to applied expression. Array.some take and expression and return true or false and end the loop.
Now filter the b array and pass an expression with array.some methods. Array.filter loop to first element of array and then array.some use property a and loop through them. If array.some found the expression condition is true it return true and end the loop now array.filter got true from array.some method and store them in an array which is r2 variable. Filter loop will continue unless all elements are covered. And then final result will store in r2 array. You can console the values of r2.


Try this example yourself. Try with less complex array nested object then move to big one.

Try to write your own approach and then write the code also you can create flowchart for this to break down a Problem and easily achieve the solution.

Comments