Analyzing and tallying the size of each filtering element

In my JavaScript code, I have an array called Projects and another one called Teams.

const Projects = [{fkTeamId: 'a'}, {fkTeamId: '8'}, {fkTeamId: 'c'}, {fkTeamId: 'a'}];
const Teams = [{TeamId: 'a'}, {TeamId: 'c'}, {TeamId: '8'}];
const output = Projects.filter(item1 => Teams.some(item2 => item2.TeamId === item1.fkTeamId))
console.log(output)

The goal is to determine the number of projects associated with each team. For example, if "TeamID: a" has 2 projects, I want to know that specifically. My initial idea was to store this information in an array and then use the .length method, but I am uncertain on how to proceed.

Currently, the code generates the following output:

Array [Object { fkTeamId: "a" }, Object { fkTeamId: "8" }, Object { fkTeamId: "c" }, Object { fkTeamId: "a" }]

How can I utilize the .length property to determine the project count for each Team ID?

In simpler terms, I am attempting to achieve something like this:

const count = [[{fkTeamId: "a"},{fkTeamId: "a"}], [{fkTeamId: "8"}], [{fkTeamId: "c"}]];

console.log(count.forEach(Team => Team.length)) 

The objective of the aforementioned code snippet is to produce an array or similar structure containing:

count = [2, 1, 1]

Answer №1

Initially, I started counting to better analyze my progress from the start and ultimately provide you with the desired Object.. Great :D

const Projects = [{fkTeamId: 'a'}, {fkTeamId: '8'}, {fkTeamId: 'c'}, {fkTeamId: 'a'}];
const Teams = [{TeamId: 'a'}, {TeamId: 'c'}, {TeamId: '8'}];
const output = Projects.filter(item1 => Teams.some(item2 => item2.TeamId === item1.fkTeamId))

var tempObj={}
var newOutput=
output.filter(a=>{
  if(!tempObj[a.fkTeamId]){tempObj[a.fkTeamId]=1}
  else{tempObj[a.fkTeamId]++}
  return tempObj[a.fkTeamId]==1
})
//console.log(newOutput) //the new output without 2 teams of same name in the array
console.log(tempObj) //object that has the team names and how many times they occured
var tempArr=Object.keys(tempObj).map(a=>tempObj[a])
console.log(tempArr) //literally what you asked for in terms of expected result
var commentQuestionAnswer=
Object.keys(tempObj).map((a,i)=>{return {teamId:a,quantity:tempArr[i]} })
console.log(commentQuestionAnswer) //for the question u sent in a comment below

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

You won't be able to view over 15 KML layers on a page that relies on Google Maps API

I've encountered an unusual issue: I need to create multiple KML layers from separate KML files and display them on a single map window. The number of files ranges from just a couple to less than fifty. Currently, my code works perfectly when given 1, ...

What is the best approach to accessing the original data stored in a data-* attribute using jQuery?

It seems I may have overlooked something, as I've been utilizing the data-* attribute, specifically data-content, with entries like "apple", "cow", and so on. However, I encountered an issue when I set my data-content to the string "null" (upon inspec ...

Creating an array in Angular is done by using the syntax []

I encountered an error and I'm not sure how to fix it. Can someone assist me? The error message reads: "Type '{ animal:[{ id : 1,name: "Elephant"},{id : 2, name: "Horse"} []; }' is not assignable to type 'string[]'. Property & ...

How to use Angular 8 Form Builder to upload an array of multiple images

My product form includes various fields like product name, description, and an array of images. Product Form Product Name - Product Description Product Purity - Product Commodity Images (Add) Checkbox 1 - Image 1 Checkbox 2 - Image 2 Checkbox 3 - ...

Tips for declaring and utilizing multiple functions within an Angular JS Factory, as well as executing one function inside another

Could someone assist me in creating multiple functions within an AngularJS Factory? I am looking to access the returned value from one function and process it in another function. I attempted the code below without success. In the following function, I wa ...

Contrasting an array of items with an array of Objects

I need to match the values in an array called ingredientName with a corresponding array of objects. Here is how they look: const ingredientName = ['chicken', 'cheese', 'tomato', 'lettuce']; let imageObjects = [ { ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...

The character count displayed in an ASP.NET text box may not match the character count of the text box on the

I've implemented a JavaScript function to show users the remaining character count on a page. However, when I validate the length server-side before inserting it into a database column, the count appears to be different. After researching online, it ...

An application running on Node.js/Express and hosted on Digital Ocean encounters the "Cannot get /" error message

Despite searching extensively online and sifting through numerous solutions to different scenarios, I remained unable to find a fix that resolved my issue. When attempting to run my server.js file locally, everything operates smoothly. However, upon transf ...

Showing canvas lines while dragging (using only plain JavaScript, with React.JS if needed)

Is there a way to add lines with two clicks and have them visible while moving the mouse? The line should only be drawn when clicking the left mouse button. Any suggestions on how I can modify my code to achieve this functionality? Currently, the lines are ...

Having trouble rendering components due to conflicts between React Router and Semantic UI React

Below is the code in my App.js: import { useRecoilValue } from 'recoil'; import { authState } from './atoms/authAtom'; import { ToastContainer } from 'react-toastify'; import { ProtectedRoute } from './layout/ProtectedRou ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

Rendering in React by cycling through an array and displaying the content

I have been working on displaying two arrays. Whenever the button is clicked, a new user is generated and added to the array. My goal is to render the entire array instead of just the newest entries. I've attempted various methods but haven't had ...

Learn how to capture complete stack traces for errors when using Google Cloud Functions

In the codebase I am currently working on, I came across a backend service that I would like to utilize for logging all errors along with their corresponding Http statuses. If possible, I also want to retrieve the full stack trace of these errors from this ...

Need help with jQuery UI and managing changing content?

Looking for suggestions on using a dynamic, single dialog that updates based on ajax calls. Is there a graceful method to adjust the height and width according to the new content? Currently encountering issues with an empty div being populated. Any assist ...

Disable link 2 when link 1 is clicked

Looking to create a feedback form with two exclusive links. Want to ensure that if someone clicks the first link, they cannot click the second link and vice versa. Interested in exploring options like using cookies to prevent multiple clicks or possibly ...

What is the reason for the absence of CORS restriction in this code snippet?

I've tested this code across various browsers and it seems to be working perfectly fine. Can someone explain why this is happening? What am I overlooking here? <html> <body> <script src="https://ajax.googleapis.com/ajax/libs/jq ...

What is the best way to verify a null value in PHP?

I'm having trouble displaying registered items on my website. I tried validating with JavaScript first, but it kept showing errors. Then I attempted validation using PHP, but that didn't work either. Every time I try to insert data into the data ...

Is your React conditional rendering malfunctioning due to state issues?

I am attempting to create a component that will only be displayed after clicking on a search button. Below is the current code that I have: Update After making some changes, I am now encountering this error: Error: ERROR in /home/holborn/Documents/Work ...

const React with several parameters

What is the recommended practice for parsing 2 parameters to a const in React? I am looking to use username and message instead of data. socket.on('updateChat', function (username, message) { addMessage(username, message); } const addMessag ...