What is the best method to condense an array or extract only the valid values?

Looking to find the total count of properties that are true from an array of objects? Here's an example:

let data = 
[
    {
        comment: true,
        attachment: true,
        actionPlan: true
    },
    {
        whenValue: '',
        comment: true,
        attachment: false,
        actionPlan: true
    }
]

An attempt was made with the following code, but it didn't work as expected:

const countObj = questionAttributes.questionMandatoryOptions.reduce((acc, curr) => {
    return {
        // intend to extract properties with true values
    };
});

If you want to achieve this for a single item in the array, you can use the following snippet:

const total =
            options[0];
        const totalelections = Object.values(
            total
        ).filter((v) => v).length;

Answer №1

If you have already discovered the solution for a single element, then all you need to do is iterate over each element in your data array and increment a counter with the result of

Object.values(item).filter((v) => v).length;

let data = 
[
    {
        comment: true,
        attachment: true,
        actionPlan: true
    },
    {
        whenValue: '',
        comment: true,
        attachment: false,
        actionPlan: true
    }
]

function countTrueProperties(dataArray: any[]): number {
    let count = 0;
    for(const item of dataArray){
        count += Object.values(item).filter((v) => v).length;
    }
    return count;
}

console.log(countTrueProperties(data));

Demo playground

Answer №2

Can be utilized with the specified ts configs:

"target": "es2019"
, or if lib includes "esnext".

For more information, visit: flatMap, flat, flatten doesn't exist on type any[]

{
  "compilerOptions": {
    "target": "es2015",
    "lib": [
      "dom",
      "esnext"
    ]
  }
}
let data = [{
    comment: true,
    attachment: true,
    actionPlan: true
  },
  {
    whenValue: '',
    comment: true,
    attachment: false,
    actionPlan: true
  }
];

const countObj = data
  .map(x => Object.values(x)) // [[true, true, true], ["", true, false, true]]
  .flatMap(x => x) // [true, true, true, "", true, false, true]
  .filter(x => x === true) // [true, true, true, true, true]
  .length; // 5

console.log(countObj); // 5

https://codesandbox.io/s/typescript-forked-xm49dw?fontsize=14&hidenavigation=1&theme=dark

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

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Highcharts3d was already defined locally, preventing the import declaration from being recognized with error code TS2440

Struggling to get my application to run in VS code due to this persistent error: error TS2440: Import declaration conflicts with local declaration of 'Highcharts3d' Any assistance in resolving this issue would be greatly appreciated. import ...

Using Angular 2 to Bind a Single Click Event to Multiple Elements

Within the component's export class, I have defined iconCheck: string;. In the constructor, I set this.iconCheck = "add_circle";. Additionally, in the export class, I have the following method: iconChange() { if(this.iconCheck == "add_circle") { ...

Troubleshooting Paths with Angular's NgFor Directive

Within my Angular project, I have implemented a basic ngFor loop to display logo images. Here is a snippet of the code: <div *ngFor="let item of list" class="logo-wrapper"> <div class="customer-logo"> & ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

Using the Amazon Resource Name (ARN) of a Cloud Development Kit (CDK) resource in a different

Having trouble obtaining the ARN of my AWS CDK stack's Step Functions state machine for my lambda function. The ARN is constantly changing and I'm unsure how to access it. I attempted to create a .env file alongside the lambda function's in ...

Exploring Nested JSON Iteration in Angular4

I am struggling to iterate through a nested JSON and extract the desired output. Can someone assist me in retrieving the bpmn:startEvent id value from the JSON provided below? { "bpmn:definitions":{ "@attributes":{ "xmlns:xsi":"h ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

Storing an image in MongoDB using Multer as a file from Angular is not working as anticipated

I'm currently dealing with an issue that I believe is not functioning correctly. I installed a library in Angular called cropper.js from https://github.com/matheusdavidson/angular-cropperjs. The frontend code provided by the developer utilizes this li ...

Issue accessing page from side menu in Ionic 2 application

I am experiencing an issue where the page does not open when I click on it in the side menu. Here is my app.component.ts file: this.pages = [ { title: 'NFC Page', component: NfcPage, note: 'NFC Page' }, ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

What is the correct approach to managing Sequelize validation errors effectively?

I am working on a basic REST API using Typescript, Koa, and Sequelize. If the client sends an invalid PUT request with empty fields for "title" or "author", it currently returns a 500 error. I would prefer to respond with a '400 Bad Request' ins ...

Discover the subsite inventory of a SharePoint site using TypeScript

Is there a way to gather all sub-sites from my SharePoint site and organize them into a list? I initially thought of using this.context.pageContext, but could not locate it. Please excuse my seemingly simple question, as I am still learning TypeScript. ...

Tips on displaying a spinner only when data is retrieved from an Http service

How can I ensure that a spinner is only shown during an HTTP service call and dismissed when my component receives data? To address this issue, I implemented a cache service to store data fetched from the HTTP service for future use. However, I want to sh ...

The method of evaluating in-line is distinct from evaluating outside of the

What causes the compiler to produce different results for these two mapped types? type NonNullableObj1<O> = {[Key in keyof O] : O[Key] extends null ? never : O[Key]} type NotNull<T> = T extends null ? never : T; type NonNullableObj2<T> = ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

A guide on dynamically showcasing/summoning icons in react by utilizing array data

QUESTION: 1 (SOLVED!) https://i.stack.imgur.com/1M1K7.png What is the best way to display icons based on an array of data codes? const data = [{ img: '01d' }, { img: '02d' }] if(data) { data.map((item) => ( <img src={`./ ...

Issue encountered with passport-local in TypeScript: Unable to utilize 'new' with an expression that does not have a call or construct signature

Currently, I am attempting to implement the passport-local package in TypeScript (version 2.0.0RC); however, a compiler error has arisen: Error TS2351: It is not possible to use 'new' with an expression lacking a call or construct signature. ...

Creating a dynamic return statement in typescript: A step-by-step guide

I am looking to dynamically set a return value to a variable based on values retrieved from an API. The current function in question uses static values: this.markDisabled = (date: NgbDate) => { return (this.calendar.getWeekday(date) !== 5 && ...