Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example:

4 Categories with Subjects
['A','B','D']
['C']
['E','F']
['G','H','I','J']

In addition to the categories, I have another set of arrays where each item can have up to four possible subjects:

3 Items with Subjects
['A','F']
['E','I','C']
['E','F','G']

My goal is to accurately count the number of items in each category. The expected results are:

Total Items: 3
Category 1: 1
Category 2: 1
Category 3: 3
Category 4: 2

However, there is an issue when items belong to multiple categories. In this case, my results become:

Total Items: 3
Category 1: 1
Category 2: 1
Category 3: 4
Category 4: 2

The discrepancy occurs because one of the items has two subjects within the same category, E and F.

Approaches Attempted

To provide some context, the categories are stored as objects in an array:

categories = [
 { name: string, subjects: string[], count: number }
]

The items follow a similar pattern:

items = [
 { subjects: Subject[] }
]

Where Subject is defined as:

{ id: string, name: string }

The issue lies in the following segment of code:

categories.map(category => 
 category.subjects.map(categorySubject => {
   if(items.subjects.map(itemSubject => itemSubject.id)
     .some(val => itemSubject.indexOf(val) === 0)) {
       category.count++;
   }
 }));

Although I initially used 'some' to approach the problem, I need to find a way to prevent double-counting for items with multiple subjects in one category. It's clear that my current method is the root cause of the error. While tweaking how the categories are organized could be an option, adjusting the items structure might also provide a solution.

Answer №1

Regarding your query, I believe this code snippet should suffice:

const categories: Array<{ name: string, subjects: Subject[], count: number }> = [];

type Subject = { id: string, name: string }

const items: Array<{ subjects: Subject[] }> = [];

function isSubjectInItem(subject: Subject, item: { subjects: Subject[] }): boolean {
    return item.subjects.some(itemSubject => itemSubject.id === subject.id);
}

categories.forEach((category, index) => {
    let count = 0;

    for (let j = 0; j < items.length; j++) {
        for (let i = 0; i < category.subjects.length; i++) {
            if (isSubjectInItem(category.subjects[i], items[j])) {
                count++;
                break;
            }
        }
    }

    console.log(`Category ${ index + 1 }: ${ count }`);
});

This implementation might be effective for now, but it could use some improvements for better readability and maintainability in the future.
Consider creating a CategoriesIndex to manage all categories and subjects, allowing for easier manipulation and understanding.

Answer №2

Upon initial inspection, this code may appear complex and difficult to decipher for those unfamiliar with its inner workings.

categories.map(category => category.count = 0);
let nextCategory = false;
let itemSubjects = items.map(item => item.subjects)
  .map(subjects => subjects.map(subject => subject.id));
for(var i = 0; i < items.length; i++){
  for(var j = 0; j < categories.length; j++){
    nextCategory = false;
    for(var k = 0; k < categories[j].subjects.length; k++){
      for(var l = 0; l < itemSubjects[i].length; l++){
        if(itemSubjects[i][l] === categories[j].subjects[k]){
          categories[j].count++;
          nextCategory = true;
          break;
        }
      }
      if(nextCategory === true){
        break;
      }
    }
  }
}

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 function 'sendEmailVerification' is not a property of the type 'Promise<User>'

Hey there, I've been working on my ionic4 app and have encountered an issue with the sendEmailVerification function. The console is suggesting that I may have forgotten to use 'await'. Any ideas on how to resolve this? Thank you. import { In ...

The for...of loop cannot be used with the .for property since it is not iterable. (Is

let arr = [{ category: 'music', views: 20 }, { category: 'abc', views: 32 }, { category: 'bob', views: 20 } ] for (const [key, value] of arr) { console.log(key, value) } console.log(Array ...

Typescript: organizing nested types within an interface

My goal is to create an interface CountersData based on my JSON data. The challenge lies in the nested id property, which contains an array of nested dictionaries. I want this property to be optional. However, I have not been successful in making it option ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

How can I obtain the rowIndex of an expanded row in Primeng?

<p-dataTable [value]="services" [paginator]="true" expandableRows="true" rowExpandMode="single"> ...</p-dataTable> There is a similar example below: <ng-template let-col let-period="rowData" let-ri="rowIndex" pTemplate="body">...</ ...

`I'm encountering issues when trying to pass an array through localStorage into a new array`

This is a complex and detailed question that I am struggling to find a solution for. Despite using deprecated mysql due to hosting limitations, the problem lies elsewhere. Part 1 involves dataLoader.php, which queries the database and retrieves posx and p ...

Displaying one out of two elements when the button is clicked

Trying to implement two buttons on the parent component, each displaying a different component - one for itemlist and the other for itemlist2. Struggling to get it right, even after following an example at https://codepen.io/PiotrBerebecki/pen/yaVaLK. No ...

Having trouble sending an email using nodejs and mailgun

Before accusing me of asking a duplicate question, I want to clarify that I have already searched for solutions and none of them worked for me. For example, I tried the solution provided in this link: Example of the domain name for mailgun before nodejs? ...

What is the official name of the key type for the Built-in Object?

There was a built-in type that I used in the past which represented the union of all possible object keys. It was named objectKey or something similar. Here is an example: type objectKey = string | number | symbol Unfortunately, I am drawing a blank on t ...

Leveraging the power of Map and Sort to display the items containing image URLs alongside their respective timestamps

I'm diving into firebase and utilizing react, and currently I've come across this snippet of code: {photos.map(url => ( <div key={url} style={card}> <img src={url} style={image} /> <div s ...

Typescript is throwing a fit over namespaces

My development environment consists of node v6.8.0, TypeScript v2.0.3, gulp v3.9.1, and gulp-typescript v3.0.2. However, I encounter an error when building with gulp. Below is the code snippet that is causing the issue: /// <reference path="../_all.d. ...

What is the proper way to utilize the router next function for optimal performance

I want to keep it on the same line, but it keeps giving me errors. Is there a way to prevent it from breaking onto a new line? const router = useRouter(); const { replace } = useRouter(); view image here ...

What is the most efficient way to convert a String to an Integer[][][] array?

Typically, the files I deal with come in the following format: {0 0},{0 0} {0 0 0 0},{0 0 0 0},{0 0 0 0},{0 0 0 0} Thus, I require an Integer[][][] to store an array of matrices. My initial attempt looked like this: String path = "file.txt"; Str ...

gulp-angular2 task is malfunctioning

Currently, I am in the process of working on a gulpfile and have written the following task: var tsProject = ts.createProject('app/Resources/public/angular/tsconfig.json'); gulp.task('angular-2', function () { var tsResul ...

Decorator used in identifying the superclass in Typescript

I am working with an abstract class that looks like this export abstract class Foo { public f1() { } } and I have two classes that extend the base class export class Boo extends Foo { } export class Moo extends Foo { } Recently, I created a custom ...

Using TypeScript with AWS Lambda: To package imports or not to package? Alternatively: Error in Runtime.ImportModule: Module '@aws-sdk/...' not found

I have been working with the code in my lambda.ts file, attempting to execute it on an AWS Lambda: import 'aws-sdk' import { /* bunch of stuff... */ } from "@aws-sdk/client-cloudwatch-logs"; import {Context, APIGatewayProxyResult} from ...

Tips for implementing the handleChange event with CalendarComponent from the PrimeReact library

Hey there! I'm currently working with the CalendarComponent from the PrimeReact library in my app. I want to update the type of event being typed in the handleChange function instead of leaving it as :any. Can anyone provide some suggestions on what s ...

The Static Interface Binding in TypeScript

I have inquired about how to extend the static functionality of existing objects in JavaScript (using TypeScript). In all examples provided here, I am utilizing Object The code below showcases a polyfill definition for ECMAScript's Object.is function ...

What is the correct way to bring in a utility in my playwright test when I am working with TypeScript?

I am working on a basic project using playwright and typescript. My goal is to implement a logger.ts file that will manage log files and log any logger.info messages in those files. To set up my project, I used the following commands and created a playwri ...

Can someone show me how to properly set up nested child routes in Angular 2?

My application structure is organized as shown below . ├── photos ├── posts ├── users │   ├── detail │   │   ├── address │   │   ├── family │   │   ├── information │   │   └ ...