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

Error TS5023 occurs when the integrated terminal in Visual Studio Code encounters an unfamiliar option 'w' while executing the tsc -w command

I am encountering an issue with the tsc -w command in the VS Code integrated terminal. However, I have successfully executed it from the NodeJs Command Prompt. `error TS5023: Unknown option 'w' Use the '--help' flag to view available o ...

retrieve document data from firestore using the service

Is there a way to get real-time data from a Firestore document using a service? According to Firebase's documentation, you can achieve this by following this link: https://firebase.google.com/docs/firestore/query-data/listen?hl=es#web-modular-api I ...

What is the best way to show an error message if a TextInput field is left blank?

I'm currently working on a mobile application using react-native, focusing on the login page. My goal is to show an error message below a TextInput field when it's left empty. To achieve this, I've been experimenting with the @react-hook-f ...

Is it possible to generate an array of strings from the keys of a type or interface?

Imagine a scenario where we have a type or interface defined as NumberLookupCriteria: type NumberLookupCriteria = { dialCode: string; phoneNumber: string; } or interface NumberLookupCriteria { dialCode: string; phoneNumber: string; } Is there a w ...

Is it possible to include if else logic code within a catch statement?

There's a nagging feeling within me that having logic code within a catch statement is not the right approach. For example, my catch block currently looks like this: try{ // do some stuff that throws some unexpected errors } ...

Implementing undefined value acceptance in yup object when using Material-UI

Even though I have clearly specified that the key is optional in my Form, for some reason my input does not accept undefined as a value. Instead, I keep getting this error message: bonusPercentage must be a number type, but the final value was: NaN (cast ...

What is the best way to use an Observable to interrogate a fork/join operation?

I have a forkjoin set up to check for the presence of a person in two different data stores. If the person is not found in either store, I want to perform a delete action which should return true if successful, and false otherwise. However, my current impl ...

Switching the Checkbox Data Binding Feature in Angular

I am looking to send a value based on a toggle switch checkbox selection between Hourly or Salary. How can I incorporate this into the form below? html <div class="row"> <div class="col-sm-6"> <div cl ...

Enhance your property by adding the isDirty feature

Managing changes to properties of classes in TypeScript can be optimized by tracking only the fields that have actually changed. Instead of using an array to keep track of property changes, I am exploring the idea of implementing an isDirty check. By incor ...

I'm having difficulty updating the Angular CLI version

I am currently running Angular CLI version 7.1.4 and I have been attempting to update to the latest version. However, each time I try to update, I encounter a multitude of errors. I have attempted using the command ng update @angular/core @angular/cli b ...

Utilizing interpolation for a CSS class defined in an external file within Angular 2

Is it feasible to send a variable to a CSS class in an external CSS file within Angular 2, such as: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', sty ...

Tips for inserting an HTML element within an exported constant

I need help formatting an email hyperlink within a big block of text. Here is the code snippet: const myEmail = '<a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e4b564f435e424b6e4b564f435e424b004d41 ...

Is it possible to use a '.JS' file downloaded through Node Package Manager (npm) directly in a web browser?

Generally, I am looking to utilize a specific library without relying on Node CMD. For instance: I aim to create a TypeScript playground without having to execute 'tsc.cmd' from "npm\node_modules", instead, I want to directly call the tsc c ...

Node.js has been giving me trouble as I try to install Inquirer

:***Hey Guys I'm Working on a TypeScript/JavaScript Calculator! ...

Issue with closing the active modal in Angular TypeScript

Can you help me fix the issue with closing the modal window? I have written a function, but the button does not respond when clicked. Close Button: <button type="submit" (click)="activeModal.close()" ...

What is the process for specifying the type for the createApp(App) function in Vue.js 3?

I'm currently working with Vue3 and Firebase using TypeScript. // main.ts import { createApp } from 'vue' import App from './App.vue' import './registerServiceWorker' import router from './router' import store f ...

Unable to display results in React Native due to FlatList not being shown

I'm a beginner to React Native and I'm attempting to create a simple flatlist populated from an API at , but unfortunately, no results are displaying. Here's my App.tsx code: import React from 'react'; import type {PropsWithChildre ...

How to dynamically inject HTML content from a child component into a different component using Angular 5

Is it possible to customize the content of a reusable header section based on the current route data in Angular? The header currently displays a title and description pulled from the route data property. My concern is how to dynamically inject different H ...

What is the best way to link multiple select tags in an HTML document?

I am working with a data grid that contains student information such as Name, Class, and Score. Each row has a checkbox for selection. The requirement is that when the user selects one or more rows and clicks on the "show information" Button, a new windo ...

Discovering the current date in Angular 8 by utilizing the form builder

Is there a way to automatically fill a form created with FormBuilder with the system's date and time when it is created, instead of the default date format? this.creationDate = moment().format(DATE_TIME_FORMAT); I want to update the creationDate fie ...