Tips for calculating the total count of a specific field within a JSON array with TypeScript

I have a JSON array.

 "user": {
            "value": [
                {

                    "customerNo": "1234"

                },
                {
                    "customerNo": "abcd"

                },
                {

                    "customerNo": "1234"

                }

            ]
        }

To find the total number of unique customers in the JSON array using TypeScript, you can do the following:

const uniqueCustomers = Array.from(new Set(json.user.value.map(item => item.customerNo))).length;
console.log(uniqueCustomers);

The output would be 2, as duplicate customer numbers are ignored.

Answer №1

Utilize the power of lodash library:

var uniqueCustomer = _.uniqBy(json.user.value, 'customerNo');
var length = uniquеCustomer.length

Check out this link for a detailed explanation on How to integrate lodash into your application.

Answer №2

To tally up the number of distinct customers, you can utilize the Array.reduce method.

const data = { 
  "user": {
      "value": [
          {

              "customerNo": "1234"

          },
          {
              "customerNo": "abcd"

          },
          {

              "customerNo": "1234"

          }

      ]
  }
};

function getCustomerCount(arr) {
  let tmp = [];
  return arr.reduce((acc, curr) => {
    if(!tmp.includes(curr.customerNo)) {
      return tmp.push(curr.customerNo);
    }
    return acc;
  }, 0);
}

let customers = data.user.value;
let customerCount = getCustomerCount(customers);

console.log(customerCount);

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

Saving a JSON object to multiple JSON objects in TypeScript - The ultimate guide

Currently, I am receiving a JSON object named formDoc containing data from the backend. { "components": [ { "label": "Textfield1", "type": "textfield", "key": "textfield1", ...

Remove an item from an array within Express using Mongoose

{ "_id": "608c3d353f94ae40aff1dec4", "userId": "608425c08a3f8db8845bee84", "experiences": [ { "designation": "Manager", "_id": "609197056bd0ea09eee94 ...

What's the best way to extract a JSON string from a specific URL?

Looking to store JSON data in an array: arr[ ] array = {"http://www.ip-api.com/json"}; How can I print the JSON data itself instead of just showing "" as a string? ...

Adjusting the date in Angular 8 by increasing or decreasing it in the dd-MM-yyyy layout with a button press

How can I dynamically adjust the date in an input box by using buttons to increment and decrement it? Below is the code snippet: prev() { let diff = 1; //1 to increment and -1 to decrement this.date.setDate(this.date.getDate() - diff ...

Error Code 1305: In MySQL version 5.5.52, the function JSON_EXTRACT is not available

Issue: Unable to use json_extract due to error. The message body looks like this. < message type = "chat" to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0730232f252d202d2b3d2c2c3f3d3d213a3d213d3a373 ...

Load data from a JSON flat file and dynamically populate new <li> elements with it

I'm attempting to utilize data from a json flat file in order to: Create new list items Fill specific classes within the newly created list items The json data appears as follows: { "event": { "title": "Title of event", "preface": "Prefa ...

Utilizing Perl to extract specific data from a JSON query

I have been working on a section of my website where I need to display information fetched from a website's Json response. The URL of the website is: . For easier code readability, you can use this JSON parser tool: . While my existing code functio ...

"Enhance Your Java Code: Beautify JSON Automatically on Save

When saving a player to a .json file, I use this method: public static void savePlayer(Player player) { final String username = player.getUsername(); final byte[] json = new Gson().toJson(player).getBytes(); final String path = "pack/players/" ...

What is the best way to transform this date string into a valid Firestore timestamp?

Currently, I am facing an issue in my Angular application that is integrated with Firebase Firestore database. The problem lies in updating a date field from a Firestore timestamp field. To provide some context, I have set up an update form which triggers ...

Encountering an error while configuring webpack with ReactJS: Unexpected token found while

I'm attempting to update the state of all elements within an array in ReactJS, as illustrated below. As a newbie to this application development, it's challenging for me to identify the mistake in my code. closeState(){ this.state.itemList.f ...

formBuilder does not exist as a function

Description: Using the Form Builder library for react based on provided documentation, I successfully implemented a custom fields feature in a previous project. This project utilized simple JavaScript with a .js extension and achieved the desired result. ...

Converting TypeScript to ES5 in Angular 2: A Comprehensive Guide

I am currently diving into Angular 2 and delving into Typescript to create simple applications within the Angular 2 framework. What I have discovered is that with Typescript, we can utilize classes, interfaces, modules, and more to enhance our application ...

Trouble with Groovy HTTPBuilder while parsing correct JSON causing errors

As a newcomer to Groovy, I am facing an issue while trying to connect to the GitHub API from a Groovy script. The problem arises when HTTPBuilder attempts to parse the JSON response. Below is a simplified version of my script: @Grab(group='org.codeh ...

Tips for accessing nested items in JSON using a foreach loop in PHP

I am dealing with a JSON structure that looks like this: {"Id":"1","Persons":[{"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}, {"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}{"Name":"Luis ...

Retrieve all existing Session Variables that start with a specific prefix

Hey everyone, I have set up a series of session variables using an id as part of the name. For example, I have these variables: $_SESSION['test_variable_1']; $_SESSION['test_variable_2']; $_SESSION['test_variable_3']; I&apos ...

Retrieving Website Information through JSON

URL: I am using python to retrieve data from the JSON file linked above. I need assistance in extracting the value of "*". Typically, I would be able to access the page content directly without needing the page ID, but in this case, I seem to have encount ...

Transforming a JSON string into an Object with a field that can accommodate two distinct structures

I am facing the challenge of utilizing the Jackson library to parse a JSON object that contains a specific field "baz" with two different structures. It could either be structured like this: { "foo": "...", "bar": "...", "baz": { "bazAttribute1" ...

`Issue Encountered When Trying to Install JSON 1.8.1 Using RubyGems

Operating on the Windows 7 64x Ultimate OS, I attempted to install the json gem in the following manner: gem install json -v '1.8.1' Encountered an issue during installation: Temporarily enhancing PATH to include DevKit... Building native exte ...

How can I create and assign types dynamically in TypeScript?

I'm working on creating an SX styling file with a style object of type SXPropsTypes. In another file, I'm having trouble accessing the style properties because the autocomplete isn't suggesting the keys of my style object. style.ts import { ...

typescript Object that consists of properties from an array with a defined data type

I have an array consisting of strings. I am trying to transform this array into an object where each string is a property with specific attributes assigned to them. export interface SomeNumbers { name: string; value: number; } const arr = ['apple& ...