How can I efficiently filter an array using key and value pairs from within nested arrays?
I am in need of a method to filter the elements of an array based on specific key-value pairs nested within another array. The key will always contain boolean values.
While there are various ways to achieve this, I am looking for a more optimized approach as performance could be impacted when dealing with a large number of records.
[
{name: 'PERSON1',
info_add: {name: 'obs', active: true, faithful: false}.........},
{name: 'PERSON2',
info_add: {name: 'obs', active: true, faithful: true}.........},
{name: 'PERSON3',
info_add: {name: 'obs', active: false, faithful: true}.........},
]
I specifically want to filter based on the active
or faithful
key within the info_add
object, depending on whether the value is true or false.
active = true => PERSON1 object, PERSON2 object
active = false => PERSON3 object
faithful = true => PERSON2 object, PERSON3 object
faithful = false => PERSON1 object
Due to the size of my array and its nested nature, I am seeking advice on the best practices for filtering objects based on active
and faithful
keys.
Currently, I am only filtering based on string values using the following method. However, I am open to exploring alternative methods to enhance filter performance.
public static filterArrayByString(mainArr, searchText)
{
if ( searchText === '' )
{
return mainArr;
}
searchText = searchText.toLowerCase();
return mainArr.filter(itemObj => {
console.log(itemObj);
return this.searchInObj(itemObj, searchText);
});
}