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

Typescript support on Emacs

"Is there a way to enable Typescript syntax highlighting in Emacs?" I have been struggling with this for quite some time. Using Emacs 24 on an Ubuntu Virtualbox VM, I can't seem to get package-refresh-contents to work as it just hangs on "Contacting ...

Issues encountered when passing JavaScript object to PHP

I'm attempting to transmit my JavaScript object to PHP using JSON.stringify() JavaScript: $('#save').on('click touch', function(){ obj = { "1" : { "1" : "hey", "2" : "hay" }, ...

There seems to be an issue with the functionality of Array.filter when trying to use it with arrays

I am facing an issue with filtering branchId from an Array. Here is the code snippet and steps I have taken. const [branchID,setBranchID]=React.useState([]); const tempTwo=[ { branchId: "61b25e0ae177d62ce4cb3b47", bra ...

Transitioning React components organized in groups to TypeScript

As I transition my react project to incorporate typescript, one challenge I encountered was adjusting the file structure. In its simplified form, here is how the original js project's file structure looked like: src components index.js inputs butt ...

What is the most effective way to split time into two separate parts?

Suppose a user enters the time as 12:34 and we need to split it into two different parts to save it in an array like [12, 34]. How can this be achieved using Angular? I attempted to split them but my solutions were unsuccessful! I am currently utilizing & ...

Is it possible to effortlessly associate a personalized string with an identifier within an HTML element utilizing Angular2?

Check out this cool plunker import {Component} from 'angular2/core' @Component({ selector: 'my-app', template: ` <div *ngFor="#option of myHashMap"> <input type="radio" name="myRadio" id="{{generateId(option[& ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

Sending JSON data through an AJAX call results in an empty array being received

Recently, I've been attempting to send data through ajax using the following information: var jsondata = {"address" : [ { "id": addid, "streetaddress": streetaddress, "city": city, "state": state, "zipcode": zipco ...

I'm in the process of putting together a node.js project using typescript, but I'm a little unsure about the steps needed to

Currently, I am working on a node.js project that involves compiling with typescript. I recently realized that there is a directory named scripts dedicated to running various tasks outside of the server context, such as seed file operations. With files now ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Error: Unable to locate Angular2 Custom Service

I have implemented a custom service to populate a list of people in my HTML. Below is the code for my custom service: app.peopleListService.ts import { Injectable } from '@angular/core'; import { Person } from "../model/peopleModel"; @Injecta ...

Compelling users to provide feedback on an App with the Ionic Framework

As a novice developer, I could use some assistance with implementing ratings in my app. My goal is to show menu items based on whether a user has given my app a 5-star rating. For instance, if a user gives a 5-star rating, I would assign the class "review ...

Is it possible to perform nested arrays joining using Php::PDO?

It may seem like a lot to ask, but I'm wondering if it's possible without having to code it myself. I have two tables: "users (ID, USERNAME)" and "pictures (ID, USER_ID, NAME)". To retrieve images of users, the query would usually be: SELECT * F ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...

Is there a way to define the length of children when performing props type checking?

I need my component to only allow for three children that are considered as type React.ReactChild. However, I'm uncertain if ReactChild is the most suitable type to validate. Essentially, these children should be three distinct sections. function Top ...

Modify the Text Displayed in Static Date and Time Picker Material-UI

Looking to update the title text on the StaticDateTimePicker component? Check out this image for guidance. In the DOM, you'll find it as shown in this image. Referring to the API documentation, I learned that I need to work with components: Toolbar ...

Problematic PHP/AJAX: How come my getAttribute function is only selecting the initial line within the foreach loop?

My goal here is to display a list of users, each with a button that sends unique IDs to the database. The issue I'm facing is that the code only works for the first user in the list and not the rest. I suspect this is because every list item has the s ...

Tips for conducting a worldwide search in Angular 2?

I'm currently navigating my way through angular2 development and I am aiming to conduct a comprehensive search within an array of JSON objects. To illustrate, consider this sample array: invoiceList = [ { invoiceNumber: 1234, invo ...

Leverage the compiler API to perform type inference

Exploring TypeScript's compiler API for basic type inference has proven to be a challenge with limited helpful information found in documentation or online searches. My goal is to create a function inferType that can determine and return the inferred ...

Struggling to incorporate method decorators to handle http errors in Angular?

My goal is to implement error handling for all http requests using custom decorators. Here's my current code snippet: createRecord(data: data) { return this.httpClient.post(`${this.apiURL}/record/`, data); } I am looking to refactor thes ...