Ways to determine the presence of a value in an array

Here is an example array:

[
  {practitioner: "place_1509136116761", H0709: false, H0911: false, H1113: false, H1315: false},
  {practitioner: "place_1509136116772", H0709: true, H0911: false, H1113: true, H1315: false},
  {practitioner: "place_1509136116698", H0709: false, H0911: true, H1113: false, H1315: true},
  {practitioner: "place_1509136116733", H0709: true, H0911: true, H1113: true, H1315: true}
]

I am looking for a way to calculate how many times the values of H0709 - H0911 - H1113 - H1315 are TRUE.

Can anyone provide assistance with this?

Answer №1

To iterate through the data array and identify all keys in the "param" object with a true value, you can utilize the array#reduce method along with array#filter.

const data = [{praticien: "place_1509136116761", H0709: false, H0911: false, H1113: false, H1315: false},{praticien: "place_1509136116773", H0709: false, H0911: false, H1113: false, H1315: false},{praticien: "place_1509136116699", H0709: true, H0911: false, H1113: false, H1315: false},{praticien: "place_1509136116734", H0709: false, H0911: true, H1113: true, H1315: false}],
      keys =['H0709', 'H0911', 'H1113', 'H1315'];

const result = data.reduce((sum,o) => {
  sum += keys.filter(k => o[k]).length;
  return sum;
},0)

console.log(result);

To tally up the count of keys with a true value, you can employ array#reduce together with array#forEach. Within the array#foreach, verify if the key holds a true value and increment the count.

const data = [{praticien: "place_1509136116761", H0709: false, H0911: false, H1113: false, H1315: false},{praticien: "place_1509136116773", H0709: false, H0911: false, H1113: false, H1315: false},{praticien: "place_1509136116699", H0709: true, H0911: false, H1113: false, H1315: false},{praticien: "place_1509136116734", H0709: false, H0911: true, H1113: true, H1315: false}];

const result = data.reduce((res,o) => {
  Object
    .keys(o)
    .forEach(k => {
      if(o[k] === true) 
        res[k] = (res[k] || 0) + 1 ;
    });
  return res;
},{});

console.log(result);

Answer №2

const elements = [{praticien: "place_1509136116761", H0709: false, H0911: false, H1113: false, H1315: false}, {praticien: "place_1509136116773", H0709: false, H0911: false, H1113: false, H1315: false}, {praticien: "place_1509136116699", H0709: true, H0911: false, H1113: false, H1315: false}, {praticien: "place_1509136116734", H0709: false, H0911: true, H1113: true, H1315: false}]

const result = {
    trueValues: 0,
    falseValues: 0
}

elements.forEach(function(element){ 
  for (property in element ){ 
    if (element.hasOwnProperty(property)) {
        if (element[property]) result.trueValues++;
      else result.falseValues++;
    }
  }
});

console.log(result);

This function calculates the number of true and false values ​​in all objects. It now checks if the property name starts with 'H'. If you need to include this condition, you can add it inside the

if (element.hasOwnProperty(property))
block.

Take a look at the updated demo here: fiddle

EDIT: Only properties starting with 'H' are considered.

Line modified in the code above:

if (element.hasOwnProperty(property) && property[0] === 'H') {

You can find the new demo at: new fiddle

NOTE: The console.log statement was added to indicate which properties are taken into account. In production, remember to comment out or remove it.

Answer №3

If you want to retrieve objects based on specific values, experimenting with filter could be the way to go

function checkValue(object) {
  return object[key];
}

var filteredObjects = myArray.filter(checkValue);
var totalOccurrencesOfSpecifiedValue = filteredObjects.length;

However, keep in mind that there are alternative methods available such as using lodash's some function.

Answer №4

                var data = [
                  {
                    doctor: "place_1509136116761",
                    H0709: false,
                    H0911: false,
                    H1113: false,
                    H1315: false
                  },
                  {
                    doctor: "place_1509136116773",
                    H0709: false,
                    H0911: false,
                    H1113: false,
                    H1315: false
                  },
                  {
                    doctor: "place_1509136116699",
                    H0709: true,
                    H0911: false,
                    H1113: false,
                    H1315: false
                  },
                  {
                    doctor: "place_1509136116734",
                    H0709: false,
                    H0911: true,
                    H1113: true,
                    H1315: false
                  }
                ]
            var result = { H0709: 0,H0911: 0,H1113: 0,H1315: 0};
                angular.forEach(data, function(obj){
                   if(obj.H0709){
                      result[H0709] = result[H0709]++;
                   }
                   if(obj.H0911){
                      result[H0911] = result[H0709]++;
                   }
                   if(obj.H1113){
                      result[H1113] = result[H0709]++;
                   }
                   if(obj.H1315){
                      result[H1315] = result[H0709]++;
                   }
                });

result will be { H0709: 1, H0911: 1, H1113: 1, H1315: 0 }

this shows that H0709, H0911, and H1113 were only TRUE once, while H1315 was never TRUE.

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

Are you experiencing difficulty loading ng-view in AngularJs?

I am new to AngularJs. I am currently using a wamp server and have successfully loaded the HTML page, but unfortunately the view is not being displayed. I have added ng-app to the body as well, but still unable to load the view. <!DOCTYPE html> ...

Ways to ascertain whether a user has successfully logged in

Just diving into Angular testing and decided to test out the checkLogin function within my application. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import {AuthenticationService} from &qu ...

Typescript's default string types offer a versatile approach to defining string values

Here is an example code snippet to consider: type PredefinedStrings = 'test' | 'otherTest'; interface MyObject { type: string | PredefinedStrings; } The interface MyObject has a single property called type, which can be one of the ...

Errors in Visual Studio regarding typescript are often not found by tsc and eslint, causing frustration for developers

Today, after restarting my computer and launching visual studio code, I encountered an unfamiliar error that I've never seen before: https://i.sstatic.net/z1vw5.png I haven't made any changes to my project's code (confirmed by running git ...

Comparing values in an array with PHP

Hello everyone, I could really use your assistance. Let's consider a scenario where I have an array. $arr = array( 1 => array( key1 => something, key2 => something, key3 => something, testkey => 3 ...

Adding a new key to a specific position in an array using Angular

After organizing my array, here is what it currently looks like: 0: Object { row: 0 } 1: Object { row: 1 } 2: Object { row: 2 } 3: Object { row: 3 } Now, I need to add a new key to position 2. The updated structure should resemble this: 0: Object { row: 0 ...

What is the best way to retrieve specific JSON data from an array in JavaScript using jQuery, especially when the property is

Forgive me if this question seems basic, I am new to learning javascript. I am currently working on a school project that involves using the holiday API. When querying with just the country and year, the JSON data I receive looks like the example below. ...

Unexpected behavior in Angular service's value exposure

I'm encountering an issue accessing values in my service from the controller. The structure of my service is as follows: angular.module('someApp').factory('someSvc', SomeSvc); function SomeSvc($http) { var colors = []; fu ...

Encountering TypeScript error 2345 when attempting to redefine a method on an Object Property

This question is related to Object Property method and having good inference of the function in TypeScript Fortunately, the code provided by @jcalz is working fine; const P = <T,>(x: T) => ({ "foo": <U,>(R: (x: T) => U) => ...

Having trouble with obtaining real-time text translation using ngx translate/core in Angular 2 with Typescript

Issue : I am facing a challenge with fetching dynamic text from a JSON file and translating it using the translate.get() method in Angular2. this.translate.get('keyInJson').subscribe(res => { this.valueFromJson = res; /* cre ...

Encountered an issue when trying to convert JSON into an array and loop through it in an HTML file using a

Currently, I am working on a project involving Angular where I am retrieving data from an API through a GET call. Specifically, one column's data is being converted from JSON to an array. However, when attempting to iterate over this array in the HTML ...

Arranging numerous arrays in a single file and organizing the populations of various states

**I just posted for the first time and I'm not sure if I did it correctly. I need to read a file and sort the list from smallest to largest based on population. However, I'm only getting Alabama showing up once. I suspect the issue may be with th ...

Experiencing issues with ng-repeat in AngularJs?

I am currently facing an issue with two tables that are rendering data through AngularJS from two separate C# methods. Both tables have almost identical structures, with the first one being used as a search field and the second one to display names. The pr ...

Transferring data from an Angular variable to an Express backend using a POST request

req.body seems to be coming up empty for me. I've tried adding content-type headers as json, but it's not making a difference. Can anyone point me in the right direction? Thank you. UPDATE: Just to clarify, my Angular frontend is successfully hi ...

Effortlessly collapsing cards using Angular 2 and Bootstrap

Recently delving into Angular 2 and Bootstrap 4, I set up an about page using the card class from Bootstrap. Clicking on a card causes it to expand, and clicking again collapses it. Now, I want to enhance this by ensuring that only one card is open at a ti ...

Lazy loading implemented with BootstrapVue's b-nav component

Having some trouble wrapping my head around the following issue: I've created a Vue.js component with tabs that have routes. I opted for a variation of the b-nav Tabs style (official docs) and it's functioning well in terms of tabs and routing. ...

Whenever a file is chosen, I aim to generate the video HTML dynamically and display the video with play functionalities using Angular 2 and TypeScript

I am attempting to allow users to select a video file and display it so they can play it after choosing the file. Below is my HTML code: <br> <input type="file" (change)="fileChangeEvent($event)" placeholder="upload file..." class=" ...

connect a column from a separate array in pdfmake

In my current project, I am looking to link the values of an array that is different from the one present in the initial two columns. Is this achievable? (The number of partialPrice values aligns with the number of code entries). Despite several attempts ...

Unlocking the full potential of AngularJS comparator

I created this jsfiddle to experiment with the AngularJS comparator functionality, but I am encountering an issue: Check out my jsFiddle Comparator here It appears that my custom comparator function 'wiggleSort' is not being called as expected: ...

Is the angular controller as syntax still necessary, or is $scope only needed for special occasions?

I have implemented angular's 'controller as somename' syntax. Consider the following function as my controller: function myCOntroller($scope) { $scope.$emit('event'); } The above function is functioning properly. I attempted t ...