I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website :

https://i.sstatic.net/myJAf.png

On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Rice checkbox, it should show all cards with the name Rice but different District names for filtering purposes.

I'm sharing my code base for reference and seeking assistance on this issue.

1. crop.model.ts

export class Crop {
    name: string;
    checked: boolean;
    district: string
    subCategory: Subcategory[];
}

export class Subcategory {
    id: number;
    name: string;
    checked: boolean;
}

2. crop.data.ts

import { Crop } from "./crop.model";

export const CROPS: Crop[] = [
    {
        name: "Rice",
        checked: true,
        district: "Thane",
        subCategory: [
            {
                id: 1,
                name: "Basmati",
                checked: true
            },
            {
                id: 2,
                name: "Ammamore",
                checked: true
            }
        ]
    }, {
        name: "Rice",
        checked: true,
        district: "Nashik ",
        subCategory: [
            {
                id: 1,
                name: "Basmati",
                checked: true
            },
            {
                id: 2,
                name: "Ammamore",
                checked: true
            }
        ]
    },
    {
        name: "Wheat",
        checked: true,
        district: "Nashik",
        subCategory: [
            {
                id: 1,
                name: "Durum",
                checked: true
            },
            {
                id: 2,
                name: "Emmer",
                checked: true
            }
        ]
    },
    {
        name: "Barley",
        checked: true,
        district: "Ratnagiri",
        subCategory: [
            {
                id: 1,
                name: "Hulless Barley",
                checked: true
            },
            {
                id: 2,
                name: "Barley Flakes",
                checked: true
            }
        ]
    }
];

3. crop.service.ts

import { Injectable } from "@angular/core";

import { Observable, of } from "rxjs";

import { Crop } from "../shared/crop.model";
import { CROPS } from "../shared/crop.data";

@Injectable({
  providedIn: "root"
})
export class CropService {
  constructor() { }

  crops: Crop[] = CROPS;

  getAllCrops(): Observable<Crop[]> {
    return of(this.crops);
  }

  getCrop(name: string): Observable<any> {
    const crop = this.crops.filter(crop => crop.name === name)[0];

    return of(crop);
  }
}

4. all-trades.component.html

<app-header></app-header>
<div
  fxLayout="row"
  fxLayout.lt-md="column"
  fxLayoutAlign="space-between start"
  fxLayoutAlign.lt-md="start stretch"
>
  <div class="container-outer" fxFlex="20">
    <div class="filters">
      <section class="example-section">
        <span class="example-list-section">
          <h1>Select Crop</h1>
        </span>
        <span class="example-list-section">
          <ul>
            <li *ngFor="let crop of crops$ | async">
              <mat-checkbox
                [checked]="crop.checked"
                (change)="onChange($event, i, crop)"
              >
                {{ crop.name }}
              </mat-checkbox>
            </li>
          </ul>
        </span>
      </section>

      <section class="example-section">
        <span class="example-list-section">
          <h1>Select District</h1>
        </span>
        <span class="example-list-section">
          <ul>
            <li *ngFor="let crop of crops$ | async">
              <mat-checkbox
                [checked]="crop.checked"
                (change)="onChange($event, i, crop)"
              >
                {{ crop.district }}
              </mat-checkbox>
            </li>
          </ul>
        </span>
      </section>
    </div>
  </div>
  <div class="content container-outer" fxFlex="80">
    <mat-card
      class="crop-card"
      style="min-width: 17%"
      *ngFor="let crop of crops$ | async"
      [hidden]="!crop.checked"
    >
      <a [routerLink]="[crop.name]">
        <mat-card-header>
          <img
            mat-card-avatar
            class="example-header-image"
            src="/assets/icons/crops/{{ crop.name }}.PNG"
            alt="crop-image"
          />
          <mat-card-title>{{ crop.name }}</mat-card-title>
          <mat-card-subtitle>100 Kgs</mat-card-subtitle>
        </mat-card-header>
      </a>
      <mat-card-content>
        <p>PRICE</p>
      </mat-card-content>
      <mat-card-content>
        <p>{{ crop.district }}</p>
      </mat-card-content>
    </mat-card>
  </div>
</div>

<app-footer></app-footer>

5. all-trades.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Crop } from 'src/app/shared/crop.model';
import { CropService } from '../crop.service';

@Component({
  selector: 'app-all-trades',
  templateUrl: './all-trades.component.html',
  styleUrls: ['./all-trades.component.css'],
})
export class AllTradesComponent implements OnInit {

  crops$: Observable<Crop[]>;

  constructor(private cropService: CropService) { }
  ngOnInit(): void {
    this.crops$ = this.cropService.getAllCrops();
  }
  onChange(event, index, item) {
    item.checked = !item.checked;
    console.log(index, event, item);
  }

}

Answer №1

A more organized arrangement of your crop data based on your requirements would look like this:

crop.data.ts

import { Crop } from "./crop.model";

export const CROPS: Crop[] = [
    {
        name: "Rice",    // Preference for Rice 
        checked: true,
        crops: [{
            district: "Thane",
            subCategory: [
            {
                id: 1,
                name: "Basmati",
                checked: true
            },
            {
                id: 2,
                name: "Ammamore",
                checked: true
            }]
         }, 
         {
            district: "Nashik",
            subCategory: [
            {
                id: 1,
                name: "Basmati",
                checked: true
            },
            {
                id: 2,
                name: "Ammamore",
                checked: true
            }]
         }
    },
    {
        name: "Wheat",
        checked: true,
        crops: [{
            district: "Nashik",
            subCategory: [
                {
                    id: 1,
                    name: "Durum",
                    checked: true
                },
                {
                    id: 2,
                    name: "Emmer",
                    checked: true
                }
            ]
        }]
    },
    {
        name: "Barley",
        checked: true,
        crops: [{
            district: "Ratnagiri",
            subCategory: [
                {
                    id: 1,
                    name: "Hulless Barley",
                    checked: true
                },
                {
                    id: 2,
                    name: "Barley Flakes",
                    checked: true
                }
            ]
        }]   
     }
 ];

You can also consider having a districts array instead of individual district fields if subcategories are consistent for each crop. Otherwise, the approach I have illustrated is a suitable solution. Your UI can be customized to display the crops data accordingly.

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

Utilize AngularJS to bind a variable and display an external HTML file without the need to open it in a browser

In my setup, I have two HTML Views - one is for application purposes and the other is for printing. Let's call them Application.html and PrintForm.html, respectively. Here is a snippet from Application.html: <!DOCTYPE html> <html> < ...

When attempting to access a static method in TypeScript, an error occurs indicating that the property 'users_index' does not exist on the type 'typeof UserApiController'

Just dipping my toes into TypeScript and attempting to invoke a function on a class. In file A: import userAPIController from "./controllers/customer/userAPIController"; userAPIController.users_index(); In file B: export default class UserApiControlle ...

I am encountering an issue where I am using Getserversideprops within a page to retrieve data from Strapi, but I am consistently

Having an issue with fetching data from a Strapi backend using getServerSideProps in Next.js. The data appears to be undefined, even though the link works correctly in the browser. I am fetching inside a page, not a component, following the method descri ...

What is the best way to determine the range in which the value falls?

Currently, I am working on validating whether a User has the required karma (reputation) to perform certain actions, such as placing a bid on an item. The karma value falls within the interval [-25; 100]. Additionally, it is noted that as a user accumulate ...

How can I retrieve the transformation matrix for a DOM element?

Is there a way to retrieve the transformation matrix of a DOM element similar to how we can do it with canvas context? Does the DOM provide a getTransform() method for this purpose? ...

Utilize Jquery to send a preset value through an ajax request

I am working on a select box functionality where the selected option is sent via ajax to a server-side script. The current setup is functioning properly. Here is the code for the select box: <select id="main_select"> <option selecte ...

Searching for multiple array elements based on their values can be achieved by using various techniques

I am trying to find a way to select multiple elements from an array that share the same value. When I use array.find(), it only returns the first element that matches the condition. For example, in the code below, only "Donald Trump" is displayed in the co ...

Combining information from two different sources to create a more comprehensive dataset

Two get requests are returning the following data: [{ id: 1, hId: 2 }, { id: 6, hId: 1 }] The second request returns: [{ id: 1, name: 'Bob' }, { id: 2, name: 'Billy' }, { id: 6, name: 'John' }] The object ...

How can I use regular expressions to locate a React JSX element that contains a specific attribute?

Currently conducting an audit within a vast codebase, my task involves searching for all instances of a component where it is utilized with a specific prop. I believe that using regex could prove beneficial in this situation; however, the challenge lies in ...

Simulation service agent partnered with openApi backend

I am currently utilizing MSW along with the OpenAPI-backend package for my project. I aim to mock both the browser server and test server using OpenAPI specifications. With an available OpenAPI definition, I generate `generated.ts` for RTK Query (which is ...

Tips on incorporating an item into an array solely when a specific condition is met

Consider the following arrow function that creates an array: const myFunction = () => ["a", "b", "c"]; I am looking to modify this function to add another element if a specific argument is true. For example, I want it to look like this: const myFunc ...

Having trouble with JavaScript in a project I'm trying to replicate

For my coding practice, I am working on a project where clicking on the images should change the main product displayed along with its color. However, nothing happens when I click on the products. Can anyone point out what I might be doing wrong? Here is ...

Answer processing for the reminder dialog is underway

When I send a proactive message to a user, I want to initiate a 'reminder dialog'. The dialog is displayed, but when processing the response it goes back to the main dialog. This is how I currently set up my bot: const conversationState = new C ...

Populate a table dynamically using JavaScript based on existing cell values

I am currently working on filling an HTML table based on the contents of its left cells. The code below creates a table that is populated with variables: <table id="myTable" ></table> <script> var rightcell = [{name : "Name ...

Retrieve information from a changing HTML table

I am working on a nodejs express project that features a Dynamic Table within my application. Users can add or remove rows and enter values into cells, but I am struggling to extract these values from the table without using jquery. My goal is to then inse ...

Creating a Typescript HttpInterceptor and ensuring its compatibility with minification techniques

Currently, I am trying to implement an Angular HttpInterceptor based on the solution provided in this Stack Overflow response: However, I am struggling with the factory method: public static Factory($q: ng.IQService) { return new AuthenticationInter ...

next-images encountered an error during parsing: Unexpected character ''

Having trouble loading images dynamically with next-images: //Working <Image src={require(`../../images/exampleImage.jpg` )}/> However, I want to use a dynamic URL like this: //Not working <img src={require(`../../images/${image}.jpg` )}/> Th ...

Lack of animation on the button

Having trouble with this issue for 48 hours straight. Every time I attempt to click a button in the top bar, there is no animation. The intended behavior is for the width to increase and the left border color to change to green, but that's not what&ap ...

Regular expression pattern for consistently capitalizing the phrases "CA" and "USA" in an address string

end_address = 'joe's home, 123 test avenue, los angeles, ca, usa 90210'; end_address = end_address.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); The outcome of this code will ...

JkMegaMenu drop-down menus in Chrome are shifting to the left when the window is resized

Currently, I am utilizing the JKmegamenu plugin to incorporate a megamenu into a website that is currently under development. The megamenu functions properly and has an attractive appearance. However, there seems to be an issue where the drop-down divs shi ...