Access an array to filter by specific key-value pairs

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);
    });
}

Answer №1

const _ = require('lodash');

var arr = [
{
    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}
}];

var activeFiltered = _.filter(arr, function(person){
    return person.info_add.active;
});

var faithfulFiltered = _.filter(arr, function(person){
    return person.info_add.faithful;
});

console.log(activeFiltered);
console.log(faithfulFiltered);

Lodash can simplify the process of filtering arrays by using the filter function. The first line serves as the implementation of lodash in NodeJS, with the rest remaining unchanged.

Within the callback function for the filter function, each element in the array can be individually assessed to determine whether it meets the conditions for inclusion in the filtered array. Returning true signifies inclusion, while returning false denotes exclusion.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

Clicking on the button in Angular 2+ component 1 will open and display component 2

I've been developing a Angular 4 application with a unique layout consisting of a left panel and a right panel. In addition to these panels, there are 2 other components within the application. The left panel component is equipped with buttons while ...

Setting all array elements to zero in C# without employing for loops

In C#, there is a shortcut to initialize an array called Buffer with all elements set to 0 without using a for loop. You can simply use the following one-liner: byte[] Buffer = Enumerable.Repeat((byte)0, 50).ToArray(); ...

What is the best way to pinpoint and eliminate a Subject from an Observable?

Currently, I am utilizing a service to gather user responses from a questionnaire. The sequence of events is outlined below: questionnaire.component.ts : serves as the main container that receives data from question.service.ts question-shell.component.ts ...

How can I replace any non-alphanumeric characters in a string with an underscore using JavaScript or TypeScript?

There is a unique string generated from an external data source that I cannot manage. The system above me necessitates the IDs to adhere to this rule: "Field names should start with a letter and can solely consist of letters, numbers, or underscores (&apos ...

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

The module named "mongoose" does not have any member called 'PaginateResult' exported

I'm facing an issue while trying to add the necessary types for "mongoose-paginate" in my Angular 4 project setup with "angular-cli". The problem arises when Webpack throws an error. import {PaginateResult} from "mongoose"; ... getAll(page: number) ...

Having difficulty incorporating an input value into an Angular function

For a school project, I am creating a login form using Angular. Below is the HTML code: <input type="text" ng-model="username" name="username" /> <input type="text" ng-model="password" name="password" /> <button (click)="submit(username, pa ...

Retrieve the value from an HTML class using Angular

The Person Object has a field called schoolId, but the School object (not shown here) contains the schoolName. I want to display the schoolName in the table data cell instead of the schoolId from the Person Object. How can I achieve this? <tr *ngFor=& ...

Typescript subtraction operation may result in Undefined

I am a beginner in the world of TypeScript and I'm currently struggling with running this code snippet: class TestClass { public t: number = 10; constructor() { this.t = this.t - 1; console.log(this.t); } } var obj = new TestClass(); ...

Troubleshooting Problem with Installing Angular2-Google-Maps Component in FountainJS Application

Using the FountainJS Angular2 generator with Typescript and Systems.js has been helpful for scaffolding my project. Check it out here However, I encountered an issue while trying to add a component to the project. Upon importing {GOOGLE_MAPS_DIRECTIVES}, ...

Unusual problem arises with scoping when employing typeguards

Consider the following TypeScript code snippet: interface A { bar: string; } const isA = <T>(obj: T): obj is T & A => { obj['bar'] = 'world'; return true; } let obj = { foo: 'hello' }; if (!isA(obj)) thro ...

What is the best way to manipulate arrays using React hooks?

Struggling with updating arrays using hooks for state management has been quite a challenge for me. I've experimented with various solutions, but the useReducer method paired with dispatch on onClick handlers seems to be the most effective for perform ...

Sorting through items within a container object

I am currently working with an object named 'docs' that contains multiple objects within it. I am attempting to determine the count of entries that have specific values for both 'exopp_rooms_id_c' and 'is_active'. While this m ...

`Square payment integration using the mean stack technology stack`

Seeking advice on how to integrate Square payment form with angular and node. The form functions properly, but upon hitting send, it fails to post to /process-payment. As a newcomer to the MEAN stack, I am unsure where to start regarding using angular and ...

Experiencing unfamiliar typescript glitches while attempting to compile a turborepo initiative

I have been utilizing the turborepo-template for my project. Initially, everything was running smoothly until TypeScript suddenly started displaying peculiar errors. ../../packages/fork-me/src/client/star-me/star-me.tsx:19:4 nextjs-example:build: Type erro ...

Angular: Datepipe displays '01/01/0001' for NULL data retrieved from Database

When utilizing the DatePipe, does Angular automatically bind '01/01/0001' if we attempt to bind a NULL date value from the database? ...

Can the nested package within the package-lock.json file be updated?

Take for instance the make-fetch-happen package within npm/node-gyp/node_modules/ directory. https://i.sstatic.net/Marw5.png I am looking to update the make-fetch-happen package due to the http-cache-semantics v4.1.0 version being marked as unsafe in thi ...

How can we design a Protobuf structure for a map that contains an array of objects as the value?

I need help with encoding a map in a protobuf format. Here is an example of the map: const newVisMap = new Map<number, IOutput[]>(); The map contains an array of objects that share a common interface, as shown below (with one optional property): int ...

Using TypeScript, you can replace multiple values within a string

Question : var str = "I have a <animal>, a <flower>, and a <car>."; In the above string, I want to replace the placeholders with Tiger, Rose, and BMW. <animal> , <flower> and <car> Please advise on the best approach ...