Determine the count of distinct elements within an array using Angular 7

Suppose I have an array containing the following objects:

arr = [{name: 'foo', number: 1}, {name: 'foo', number: 1}, {name: 'bar', number: 1}]

How can I determine the count of foo in this array without explicitly passing the name?

search(name, arr) {
    let fooCount = 0;
    let barCount = 0;
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].name === 'foo') {
        fooCount++;
      } else if (arr[i].name === 'bar') {
        barCount++;
      }
    }
    return { foo: fooCount, bar: barCount };
}

This enables me to call the search() function and obtain counts for both foo and bar from the array.

Answer №1

let itemsArray = [{
  name: 'apple',
  quantity: 5
}, {
  name: 'banana',
  quantity: 2
}, {
  name: 'orange',
  quantity: 3
}]

function calculateTotal(input) {
  var totalQuantity = {};

  itemsArray.forEach(item => {
    if (totalQuantity[item.name]) {
      totalQuantity[item.name] += item.quantity;
    } else {
      totalQuantity[item.name] = item.quantity;
    }
  });

  return totalQuantity;
}

var finalResult = calculateTotal(itemsArray);
console.log(finalResult);

You can loop through the items and sum up the quantities for each name that matches. I hope this meets your requirements, but feel free to reach out if you need more clarification.

Answer №2

Utilize the filter method to achieve this

let items = [{name: 'foo', number: 1}, {name: 'foo', number: 1}, {name: 'bar', number: 1}]

let total = items.filter(item => item.name === "foo").length;
console.log(total)

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

Tips for categorizing the properties of an object based on their types

interface initialStateInterface { user: object; age: number; } const initialState = { user: { username: "", email: "" }, age: 0, }; In this code snippet, I have defined an interface type for the initial state containing a user ...

What could be causing my node server to display a blank page when it is pointing to the /dist folder of an Angular application?

Currently, my node server setup is as follows: const express = require('express'); const app = express(); app.get('*', (req, res) => { res.sendFile(__dirname + '/dist/page/index.html'); }) app.listen(3335, () => { c ...

What is the best method for incorporating an Angular Component within a CSS grid layout?

I recently started learning Angular and am currently working on a project that requires the use of a CSS grid layout. However, I'm facing an issue with inserting a component inside a grid area specified by grid-area. My attempt to achieve this in app ...

What is the process for creating a standard component in React Native?

Creating a generic component is my goal, but I am unsure of how to proceed. Any advice? Model: export interface ISelectOptionsRLV<T, C> { data: T[]; onPress: (option: C[]) => void; } GenericComponentList: import { StyleSheet, Text, View, Fla ...

After deleting all the duplicates, the array is now empty

I've been working on removing duplicate entries from an array of objects, specifically targeting instances where the infoPageId appears more than once. Initially, everything was running smoothly with static data. However, after switching to calling m ...

How can methods from another class be accessed in a TypeScript constructor?

I need to access a method from UserModel within the constructor of my UserLogic class. How can I achieve this? import { UserModel, ItUser } from '../../models/user.model'; export class UserLogic { public user: ItUser; constructor() { ...

Renew subscription following interruption

I need to trigger the updatePosition function when the mouseMove event occurs on the document, but not when it is emitted from the testEl.current element: const cursor$ = fromEvent<MouseEvent>(document, 'cursor') const scroll$ = fromEvent(d ...

Creating a simulated constant class in Angular 2+ for handling environment variables

Can anyone assist me with writing unit tests for functionalities that depend on the current environment? I am struggling to force a constant environment to return specific values in my source code. Here is the component code I need to test: import { Compo ...

Utilize JavaScript API for generating and retrieving XSD schema and XML documents

Are there any stable JavaScript APIs that can be used to generate and read XSD schemas and XML documents? My specific requirement is: Allow one user to define/generate an XSD schema through a UI. Later, allow another user to provide appropriate data ...

What is causing the issue of URL parameters becoming undefined when performing service injection in the app component?

When working with a service that reads parameters from the URL, everything seems to be functioning properly until attempting to inject the service into the constructor of the app.component.ts file or trying to call a service method from the app.component.t ...

The term 'XInterface' is not recognized in Typescript

Having some issues with my code here. I've defined a class and an interface, but Visual Studio is giving me an error saying it can't find the name 'RouteInterface'. I'm stumped as to why. import {Student} from './student&apos ...

Tips for submitting a request following a change in the variable

I am in the process of developing a React application and I have implemented Auth0 for authentication. My goal is to initiate an HTTP request upon page refresh, but only if the variable isLoading is false. This way, I can access the user object once the ...

Guide on achieving horizontal scrolling in Ionic 3

Check out this image I have a list of 10 names in an ion-scroll, but they are appearing on separate lines like paragraphs. Below is my HTML code: <ion-scroll scrollX="true" style="width:100vw; height:50px" > <ion-row class="headerChip"& ...

Leverage the useParams data to serve as a state object key in the useSelector function using TypeScript

Looking to access state data using a key obtained from useParams? Here's an example: export const MainPageSection = (props:MainPageSectionPropsType) => { const params = useParams(); const currentSection = params.section const excursions ...

When you subscribe to a forkJoin, you will receive an error notification

Trying to determine when all my observables have returned their values is a challenge I'm facing. Here's my approach after including import { Observable } from 'rxjs/Rx';: let observables:any[] = []; observables.push(this.getV ...

Enhancing the type safety of TypeScript Generics

Uncertainty looms over me - am I committing an error, or is this all part of the plan... Within my academic domain class Collection<E> { ... } Lies a function public Insert(item: E): void { ... } I construct a specific instance of my list const ...

Can you please explain the distinction between the .ts and .tsx file extensions? They are both commonly used for TypeScript files in a React environment, but what is the specific use case for each

Hello, I'm in the process of learning React and as I work on my project, I've noticed files with both the .ts and .tsx extensions. I'm a bit confused about when to use .ts versus .tsx. Any guidance on this topic would be greatly appreciated. ...

Encountering an Error in Angular 2 When Handling Observable Returns

Below is a snippet of code that I am working with: import { Injectable } from '@angular/core'; import { Router, CanActivate } from '@angular/router'; import { Angular2TokenService } from 'angular2-token'; import { Observable ...

Broadcast signals to an overarching frame

I have successfully embedded a chatbot (Angular 14 app) in an iframe and now I need to determine whether the frame should be minimized so it can fit within the parent container. My goal is to send custom events to the receiving frame. let iframeCanvas = do ...

Is there a way to create an automatic save feature that resets whenever the form is continuously updated?

Currently, I am developing an Angular 9 application with a reactive form. The goal is to automatically save the form data to the server every 3 seconds after the last change made to any of the form fields. However, I want to ensure that this 3-second time ...