Tips for obtaining the unique array element lengths in a JSON array

How can I determine the number of active users in a JSON array that includes both active and inactive user statuses?

{
  "body": {
    "existing_users": [
      {
        "product": "Pack-2",
        "user_status": "Inactive"
      },
      {
        "product": "Pack-1",
        "user_status": "Active"
      },
      {
        "product": "Pack-3",
        "user_status": "Active"
      },
      {
        "product": "Pack-5",
        "user_status": "Active"
      },
      {
        "product": "Pack-1",
        "user_status": "Inactive"
      },
      {
        "product": "Pack-1",
        "user_status": "Active"
      }
    ]
  }
}

The JSON array above contains information on product and user status. I want to specifically calculate the count of active users within this array.

I attempted to use the spread operator:

console.log(...this.user.body.existing_users);

This provided me with a list of all users, but now I need to filter only the active users based on their user status.

Check out the stackblitz link for more details!

Answer №1

Give this a shot

countActiveUsers() {
  const activeUsers = this.users.filter(
    user => user.status === 'Active'
  );

  console.log(activeUsers.length);
}

Answer №2

The filter method can be handy when you need to remove any Inactive users from a list.

const active_users = this.user.body.existing_users.filter(user => user.user_status !== "Inactive")
console.log(...active_users);

Answer №3

const userStatus = {
  "results": {
    "users_list": [
      {
        "name": "Anna",
        "status": "Active"
      },
      {
        "name": "Bob",
        "status": "Inactive"
      },
      {
        "name": "Charlie",
        "status": "Active"
      }
    ]
  }
}

console.log(userStatus.results.users_list.filter(user => user.status === "Active").length)

Answer №4

  var JSONobject = { 
"body": {
    "existing_users": [
      {
        "product": "Pack-2",
        "user_status": "Inactive"
      },
      {
        "product": "Pack-1",
        "user_status": "Active"
      },
      {
        "product": "Pack-3",
        "user_status": "Active"
      },
      {
        "product": "Pack-5",
        "user_status": "Active"
      },
      {
        "product": "Pack-1",
        "user_status": "Inactive"
      },
      {
        "product": "Pack-1",
        "user_status": "Active"
      }
    ]
  }
}
}

function countActiveUsers(){
    var activeCount = 0;
    for(i=0;i<=JSONobject.body.existing_users.length - 1;i++){
        if(JSONobject.body.existing_users[i].user_status == 'Active'){
            activeCount++
        }
        
    }
    console.log(activeCount);
}
countActiveUsers();

You iterate through the object to check the user status and increment the counter for each active user. Upon completion, the count variable contains the number of active users.

If you wish to have a list of all the active users, you can use the following approach:

function getActiveUsersList(){
    var activeUsersList = [];
    for(i=0;i<=JSONobject.body.existing_users.length - 1;i++){
        if(JSONobject.body.existing_users[i].user_status == 'Active'){
            activeUsersList.push(JSONobject.body.existing_users[i]);
        }
        
    }
    console.log(activeUsersList);
}

In this scenario, the array activeUsersList stores all objects of active users.

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

JSP Implementation of a Gravity-Driven Dynamic List

I am looking for a way to automatically populate a dropdown list within a JSP page form using values retrieved from a database query. The challenge is that only a limited number of rows are being pulled from the database based on other form inputs. I am no ...

Encountering a RangeError in Angular due to exceeding the maximum call stack size after removing distinctUntilChanged() from a formControl value change subscription

In the scenario where I have a parent and a child angular component, each containing their own set of form fields, I implemented change listeners in both components to monitor changes in form control values and disable certain fields based on user input. ...

Tips for extracting a value from a geojson response using a specific key

When analyzing the geojson response below, I am trying to access the following: Type and Segments To achieve this, I attempted the following: return data["type"] //does not work, error received return data["features"][0]["properties"]["segments"] ...

Avoiding special characters in URLs

Is there a way to properly escape the & (ampersand) in a URL using jQuery? I have attempted the following methods: .replace("/&/g", "&amp;") .replace("/&/g", "%26") .replace("/&/g", "\&") Unfortunately, none of these are y ...

Create an input box with a designated class

When I click the button in my HTML and JavaScript code below, I am able to dynamically add a text field and radio button. This functionality is working properly. However, I also want the newly generated text field to have the same font size and appearance ...

How to access a controller function within a recursive directive template in Angular version 1.3?

In my parent directive, I am able to access controller functions using the $parent operator. However, this method does not work in recursive child directives. Here is a shortened example of the issue: // Sample controller code (using controllerAs):--- va ...

How to dynamically display content based on option selection in AngularJS using ng-show

I am trying to create a functionality where my input field is bound to my select option. When the select option is set to Yes, I want the input field to be visible, and when it's set to No, I want the input field to be hidden. (function(){ var app ...

I had hoped to remove just one item, but now the entire database is being erased

I present it in this way <tr v-for="(foodItem, index) in filteredFoodItems"> <td>{{ foodItem.name }}</td> <td>{{ foodItem.price | currency('£') }}</td> <td>{{ foodItem.category }}< ...

When attempting to display a JSON array, a variable defined as numeric transforms into NaN

I'm attempting to split a JSON array into three-column Bootstrap rows using the code below. My approach involves increasing a numeric variable to 3, adding a new row div, and then setting it back to 1. However, I am encountering an issue where the va ...

Node.js POST request only executes successfully on the second attempt

I am facing a peculiar issue where upon submitting a form, it redirects to the form action URL and then displays a blank page. However, upon reloading the page, the data is displayed. index.jade - http://172.18.0.60:3000/ form#command(action='runc ...

"Utilizing JavaScript to locate a corresponding row in a table within an MVC view

I am currently updating my row using Ajax call and now I want to update the row with the new data without refreshing the page. Right now, I am matching based on DisplayName but I would like to match it with the ID since it's unique and the ID is conta ...

What is the best way to ensure the footer remains in an automatic position relative to the component's height?

I am struggling to position the footer component correctly at the end of my router-outlet. After trying various CSS properties, I managed to make the footer stay at the bottom but it acts like a fixed footer. However, I want the footer to adjust its positi ...

Obtaining the "match" object within a Custom Filter Selector on jQuery version 1.8

Here's a helpful resource on Creating a Custom Filter Selector with jQuery for your reference. A Quick Overview: If you're unfamiliar with jQuery's Custom Filter Selectors, they allow you to extend jQuery’s selector expressions by addi ...

Receiving array data in a Javascript function and storing it within a variable

Hello everyone, please take a look at my code below. I am attempting to pass PHP array values to a JavaScript function. When I run the script, I receive alerts for parameter0=1, parameter1=2, and parameter2=3 separately. What I am trying to achieve is to ...

Creating a popup window for multiple file uploads in ASP.NET using VB.NET

Hello, I am trying to create a popup window with multiple file upload options. When the 'UploadDocument' button is clicked, I want the popup window to appear. I have attempted to do this but it is not working as expected. Currently, the popup ap ...

What strategies can I use to refactor this controller in Angular 1.5 to make it more concise and efficient

I am encountering an issue with a component I have that contains a button. Whenever the button is clicked, it triggers one of two backend services depending on where the component is located. To achieve this, I am currently passing a flag to the component ...

Can an additional height be added to the equalizer to increase its height?

Is it feasible to append an additional 35px to the height determined by Foundation Equalizer? For instance, if Equalizer computes a height of 350px, I would like to increase it by 35px. This means that the resultant style should be height: 385px; instead ...

Determining if an emitted event value has been altered in Angular 4

I am currently working on an Angular 4 project. One of the features I have implemented is a search component, where users can input a string. Upon submission of the value, I send this value from the SearchComponent to the DisplayComponent. The process of ...

Triggering the open() function within an Ajax request

Upon experimenting with the method open(), I discovered that it requires a URL file as an argument. For instance, I have two functions named generateGeometricShapes() and colorShapes(). I am contemplating whether I should create separate files for each fu ...

The download attribute is not functioning properly on both Chrome and Edge browsers

I've been trying to use the download attribute, but it doesn't seem to be working. I have also attempted to use the target attribute to see if there are any issues with downloading from the server or from a web (https) source. Unfortunately, noth ...