How to find the number of distinct elements in a JSON array by considering 2 different keys in JavaScript

The JSON array provided here contains all the metrics and dimensions available from the Google Analytics API v3:

To create a table showing the number of dimensions and metrics, you can use the following code:

var results = new Array();
for (var j = 0; j < output.items.length; j++) {
    var key = output.items[j].attributes.type.toString(); 
    if (!results[key]) { 
        results[key]=1 
    } else { 
        results[key]=results[key] + 1; 
    } 
}

The outcome is: [DIMENSION: 244, METRIC: 206]

In addition to this data, it's also possible to determine the status of each dimension or metric as public, deprecated, or any other classification that may be assigned by Google. To achieve this, you can use the following code:

var statusDimensions = new Array();
for (var j=0; j<output.items.length; j++) {
    var key = output.items[j].attributes.type.toString(); 
    var subKey = output.items[j].attributes.status.toString(); 
    if (key != "METRIC" && !statusDimensions[subKey]) {
        statusDimensions[subKey] = 1
    } else {
        statusDimensions[subKey] = statusDimensions[subKey] + 1;
    }
}

However, the result currently shows: [PUBLIC: 414, DEPRECATED: 36], indicating an unexpected behavior in the evaluation of the condition key != "METRIC".

  1. What could be causing this issue?
  2. Is there a way to combine both type and status information in a single loop and array?

Answer №1

It seems like you're looking to exclude items with a type of "METRIC".

In your current code, when the type is "METRIC", the else statement is executed, consequently incrementing the counter.

An alternative approach could be:

var statusDimensions = {};
for (var j=0; j<output.items.length; ++j) {
  var type = output.items[j].attributes.type,
      status = output.items[j].attributes.status;
  if (type != "METRIC") {
    statusDimensions[status] = (statusDimensions[status] || 0) + 1;
  }
}

I've also used an object {} instead of an array []. It's generally recommended to use objects when keys are not just positive integers.

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

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

Unable to successfully transfer a document

I am looking to upload a file onto my server. Here is what I have attempted: <input (change)="uploadImage($event.target)" hidden accept="image/*" #uploadProfileImage type="file"> uploadImage(event) { const profileImage = event.files.item(0); t ...

What is the best way to handle mapping an array with uncertain levels of nesting?

My task involves rendering an array of comments in ReactJs, each of which can have nested comments at unknown levels. I am struggling to figure out how to display these comments with their respective nesting levels. comment 1 -- comment 2 -- comment 3 --- ...

Unable to Load Complete Calendar

I'm having trouble getting my full calendar to appear. Can anyone help me with this issue? See the error below. https://i.sstatic.net/b5QG8.jpg ...

Creating a file solely for route definitions and then employing them within index.js

My index.js file contains the following routes: import { createRouter, createWebHistory } from '@ionic/vue-router'; import { RouteRecordRaw } from 'vue-router'; const routes = [{ path: '', redirect ...

Dynamically adjust row height in AG Grid within an Angular application based on the visibility of other columns

My current AG-Grid version is 21.2.1, and I am unable to upgrade it for certain reasons. I have successfully implemented wrapping cell content to ensure all content is visible. Additionally, I have buttons in my application to toggle the visibility of col ...

Executing mailto URLs from action method

As a newcomer to MVC, I am looking to create an action method in MVC that triggers Mailto:?body=body goes here.&subject=test subject, allowing the default mail client to automatically populate the user's email. Currently, I have a List<String&g ...

Combining arrays of objects while maintaining data integrity in PHP

I am dealing with two arrays of objects: Array One: $array1 Array ( [0] => stdClass Object ( [id] => 100 [name] => John Doe ) [1] => stdClass Object ( [id] => 101 ...

typescript: define the type of an object that behaves like a map

My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T. Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it ...

Display the resourceTimeGrid in the month view using Fullcalendar's rendering feature

Hey everyone, I'm trying to divide a month into 4-5 weeks with each week having 7 days. I'm struggling to figure out how to display the entire month in this format. Currently, only the current week is shown where each column represents the days o ...

Flex dimensions causing design elements to break in React Native

When using both import {dimension} from 'react-native' and flex:1 in a CSS style, the design may break on certain devices, especially when there is an input field present in the JavaScript. This issue is unexpected as CSS should typically be stra ...

I need to retrieve the Instagram follower count for a specific user using JavaScript based on their user ID

I'm looking to design a form that allows users to input their Instagram ID and receive the exact number of followers without the "k" abbreviation. However, I am unsure how to achieve this. Any guidance on how to accomplish this would be greatly apprec ...

Tracking website visits using JavaScript cookies

Is there a way to track the number of times a user visits a page, but only increment the visit count if more than 30 minutes have passed since their last visit? If so, how can this be accomplished? Currently, I am using the following code snippet to set ...

What is the technique for performing asynchronous querying of multiple SQL databases?

Currently, I am in the process of developing a web application using nestjs and typeorm. I have been contemplating the functionality of the following code: const r1 = await this.connection.query(sqlA) const r2 = await this.connection query(sqlB) Does th ...

Utilizing dynamic attributes within the CSS styling function

I encountered an issue when attempting the following code. It doesn't seem to be working properly. Could you provide some assistance in figuring out why? var propertyName = 'left'; var propertyVal = $("body").width(); $('nav').cs ...

Discovering a td element with a sophisticated criteria using jQuery

Here is an HTML snippet taken from a table: <td> <a href="xxa"> </td> <td> <a href="xxy"> </td> I am looking to target all td elements that contain an 'a' element with an href attribute starting with "x ...

I am experiencing challenges with utilizing moment and angular filters

I was able to get this code working perfectly before the recent jsfiddle update. However, now it seems to be causing issues. Any assistance would be greatly appreciated. Let's start with the HTML code: <div ng-app="app" ng-controller="ctrl"> ...

Getting the UTC time using JavaScript's new Date() method

Despite my thorough search, I have been unable to find a satisfactory solution. My requirement is to obtain the current time in UTC and then subtract a specified number of days (let's say 2 days). For instance, if today is March 25th, I want to retrie ...

Challenges with JavaScript calculations on dynamic HTML forms

Currently, I am immersed in a project focused on creating invoices. My progress so far involves a dynamic form where users can add and remove rows (as shown in the snippet below). I'm encountering an issue with my JavaScript and I could use some ass ...

Is there a way to retrieve items from an array within a query?

Currently, I am immersed in a school project that involves analyzing logfiles generated by salt-stack. My setup includes a MongoDB and the MONGO_FUTURE_RETURN Returner in salt-stack. The goal is to use a Python script to analyze these logfiles, with basic ...