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

Exploring Paths in a JSON Structure using Scala and a List

When working with Play Scala, we can navigate through properties in an object using the \ method: val name = (json \ "user" \ "name") If our path is defined in a list, how can we navigate to the node? val path = List("user","name") val n ...

Storing data from a service into an array in Angular: Best practices

I have a service that provides getter and setter methods, returning id: number and title: String values from my dialog component. I am trying to save these responses into my data array but struggling to achieve it. For instance: 0: {id: 0, title: &qu ...

How is it possible that there is no type error when utilizing copy with spread syntax?

When I use the map function to make a copy of an array of objects, why doesn't it throw an error when adding a new property "xxx"? This new property "xxx" is not declared in the interface. interface A{ a:number; b:string; }; let originalArray:A[] ...

The Vercel error indicates that the file or directory '/var/task/node_modules/shiki/themes/one-dark-pro.json' does not exist

import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype ...

Developing Designs in the Angular versions 5/6

I'm encountering an issue with displaying the answer from the backend (JSON). Here is the JSON data received from the server: { "items": [ { "countryId": 1, "countryName": "Особь без подданства", "countryIdEDBO": -1, ...

"Discovering the value of the nth node in a linked list with Ruby

My data response is structured like a tree in JSON format. { "id": "", "node": [ { "id": "", "node": [ { "id": "", "node": [] } ] } ] } I am trying to acc ...

Guide to Utilizing the Dracula Graph Library in Angular

Recently, I stumbled upon a JavaScript library that seems to be an ideal fit for my project. The library can be found at: After installing the necessary libraries using npm - npm i raphael graphdracula - new folders were created in node_modules and th ...

Tips on how to interpret this JSON data sample

Initially, I treated it as an array and inputted _price1=[venues valueForKey:@"price_total”]; Upon executing this code, I was expecting a count of 6 as the output, however, the actual output was 1. NSLog(@"%lu", (unsigned long)_price1.count); The re ...

Having trouble retrieving values from JSON properties

My mind is boggled by this issue, and I have a feeling it's just a simple oversight! I'm dealing with a service that sends back a JSON object: [{"accountId":"0000004000006195","title":null,"firstName":"JOE","middleName":"BLOG","lastName":"BLOGG ...

How to fix an unresolved TypeScript import?

Within my node_modules directory, there is a package that contains the following import statement: import { x } from 'node_modules/@types/openfin/_v2/main'; Unfortunately, I am receiving an error message stating "cannot find module 'node_mo ...

The labels on the viewcontroller take a considerable amount of time to load with

I am encountering a challenge with the slow loading of labels in my view controller. In this script, a userid is sent to a php script which then retrieves data related to that userid in an array. The data is sent back as a json response to the app. Howeve ...

Nestjs RabbitMq Microservices

I'm currently developing a microservice that is responsible for receiving messages from RabbitMQ. However, I am encountering an error message as follows: ERROR [Server] There is no matching event handler defined in the remote service. Event pattern: u ...

Converting JSON data into a table using jQuery, with certain columns hidden from view

I am currently working on developing a mobile app using jQuery Mobile and JSON. I have encountered two separate questions: 1) I have a JSON data set which includes fields such as id, name, surname, point, and mail. In my table that lists this data, I init ...

Error occurred during the Uglify process: Unable to access the 'kind' property as it is undefined

I developed a project using TypeScript (version 3.9.3) and Node (version 10.16.3), but now I want to minify the code by converting it to JavaScript and running UglifyJS. However, after going through this process, the services that were functioning properly ...

Issue with integrating CrunchBase API and making AJAX requests using jQuery's $.getJSON method

Can someone help me figure out why my attempt to display an alert with the "name" is not working correctly? $(document).ready(function() { $.getJSON("http://api.crunchbase.com/v/1/companies/permalink?name=Google", function(data) { alert( ...

Utilizing AngularJS to make an API call with $http method and handling a

I am attempting to make a call to my webservice using "$http". When I use "$ajax", it works fine. Here is an example of jQuery $Ajax working correctly: $.ajax({ type: "Get", crossDomain: true, contentType: "application/json; chars ...

Guid field becomes blank when sending an API request with invalid characters

My API is hosted on an IIS Server. When I send a request to a URI with the following parameters: {"CurrentTime":"2013-09-23 13:05:52", "Measurement":[{"Comment":"Test Comment","RecordIdentifier":"7F54BF3C-6022-423B-8B8F-0121BA2AF516"}], "Source":"ABC","D ...

Ensure that PHP errors are reported in JSON format, following the standard content-type guidelines

When working with AngularJs for a single page application that communicates with serverside PHP via JSON, I encountered an issue regarding error reporting from PHP. The PHP header sets JSON, but the error reporting settings are: php_flag display_errors 1 ...

issue with eval() function

I am attempting to convert a JSON string from my .php file using the eval() function, but it is not working. The browser console shows a SyntaxError: expected expression, got '<'... However, when I comment out the line where eval() is used an ...

Tips for serializing canonical/normalized JSON data using PHP

In PHP, the order of keys in JSON is not significant. The json_encode function will use the internal order of keys when converting to JSON format. It is important for me to ensure that identical JSON data is always serialized in the same way. Take for exam ...