Looking for assistance with counting an array in AngularJS?

Here's an example of an array I have:

vm.names = ['A', 'A', 'B', 'B', 'C', 'C', 'C'];

To count the items in the array, I currently use this approach:

vm.a = [];
vm.b = [];
vm.c = [];

for (var i = 0; i < vm.names.length; i++) {
  if (vm.names[i] === 'A') {
    vm.a.push(vm.names[i]);
  }
  if (vm.names[i] === 'B') {
    vm.b.push(vm.names[i]);
  }
  if (vm.names[i] === 'C') {
    vm.c.push(vm.names[i]);
  }
}

After counting, I render it in HTML like this:

{{ vm.a.length }} //2
{{ vm.b.length }} //2
{{ vm.c.length }} //3

However, I feel that there may be a better way to achieve this. If you have any suggestions, please let me know.

Answer №1

If you want to dynamically generate arrays, you can utilize the powerful reduce function.

data.names = ['A', 'A', 'B', 'B', 'C', 'C', 'C'];

data = data.names.reduce(function(object, current) {
  object[current.toLowerCase()] = object[current.toLowerCase()] || []
  object[current.toLowerCase()].push(current)
  return object;
}, data)

console.log(data.b.length)
console.log(data.c.length)

Answer №2

In situations like this, it is more efficient to utilize the switch statement rather than using multiple if conditions.

for (var j = 0; j < viewModel.display.length; j++) {
    switch (viewModel.display[j]) {
        case "X":
            viewModel.x.push(viewModel.display[j])
            break;
        case "Y":
            viewModel.y.push(viewModel.display[j])
            break;
        case "Z":
            viewModel.z.push(viewModel.display[j])
            break;
        default:
            console.log("unrecognized character")
    }
}

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

What is preventing window.scrollTo() from being executed?

I have implemented Bootstrap's Buttons plugin to toggle the state of a custom checkbox. When the button is toggled on, a hidden element should appear at the top of the page and then the page should scroll to the top. Similarly, when the button is togg ...

Utilizing AJAX and Javascript to assign text file contents to a JavaScript variable

After attempting to extract a list of words from a txt file and store it in a JavaScript variable for future use, I've encountered an issue. The problem lies in my inability to transfer the variable outside of the onreadystatechange function. Could th ...

Remove any div elements that do not contain any content

I have a method on my front end that receives HTML as a string from the backend Here is the code snippet: private async tryGetOooMessage(employeeId: string): Promise<string> { try { return await firstValueFrom(this.messages.getOutOfOfficeI ...

Error updating model: The `teams` model cannot be modified once it has been compiled

After spending hours researching on StackOverflow, I came across numerous articles related to my issue. However, I am still unable to identify what mistake I have made here. Here is my code: models/Team.js const mongoose = require('mongoose'); ...

Using Firebase to connect and disconnect from state in React with Re-base

I'm encountering some issues with React and Firebase while using the re-base module. When attempting to retrieve content from Firebase across different components in my app, I run into a problem. On one component/"page," which is home, I have the abi ...

Modification in AngularJS form validation: $dirty value alteration triggered by ui.router state transitions

Here's my scenario : I'm working on a complex multi-step form using ui-router, utilizing ng-form to validate input data with AngularJS. Whenever a user clicks on the "Next section" button, I send the form data to the server to save progress in c ...

What is the url of the file at input.files[i]?

I've encountered an issue with my JavaScript code. Currently, when a user uploads a file, the code grabs the file name. However, I need it to fetch the file's URL on the user's PC instead. How can I implement this? This is my code snippet: ...

What are the steps to organize a table's column of ants by date?

My goal is to organize the information in an antd table based on a Date column. I attempted to use the code snippet sorter: (a, b) => new Date(a) - new Date(b) for sorting purposes. Unfortunately, my attempts to address this issue can be found here bu ...

In AngularJS, leverage the scope parameter within the link function to access the property of the parent controller

I faced a challenge in my application and simplified it to the following scenario. <body ng-controller="MainCtrl"> <input type="text" ng-model="color" placeholder="Enter a color"/> <input type="text" ng-model="name" placeholder="E ...

Having trouble retrieving the value of an HTML form element through AJAX

I am currently working on incorporating a message system into my project using AJAX. However, I have encountered some difficulties as I am new to AJAX. The code I have is able to successfully send input data from the MsgMain.php file to MsgInsert.php. But ...

Error in Displaying Vuetify Child Router View

I am currently working on integrating a child router-view to be displayed alongside surrounding components. Here is an overview of my routing setup: { path: "/login", name: "TheLoginView", component: TheLoginView, }, { path: "/dashboa ...

Using ThreeJS in an iframe on a mobile device can lead to crashes in the browser due to multiple

I am encountering an issue with my ThreeJS based pages that are included via Iframe into other pages. The problem arises when switching between the two pages with ThreeJS Iframe on a mobile phone (specifically an iPhone 7 with just 1GB RAM). After two or ...

Emulating a Javascript API request

I'm looking to practice simulating API calls for a VueJS application. Currently, I am fetching data from a hardcoded JSON file that I've created. Within my App.vue: <template> <p>{{ teams.yankees.city }}</p> // Output will b ...

How to Build an Express.js Query by Using a URL Parameter?

Is there a way to retrieve specific data from my MongoDB database based on the URL? For example, if I navigate to localhost:3000/phones, I want to fetch all entries with the category "phones", and if it's localhost:3000/laptops, I need data related to ...

Keep your information current effortlessly with automatic AJAX updates

Below is the code I am currently using on my website: <?php $url = "https://www.toontownrewritten.com/api/invasions"; $data = json_decode(file_get_contents($url)); if (!empty($data->invasions)) { echo "<h1 style='text-align:center;margi ...

Comparison of performance between virtual dom and dirty-checking

As a newcomer to the world of React, I am very curious about the performance differences between React's virtual DOM and Angular's dirty checking method. React utilizes a “diffing” algorithm. a. How does this algorithm work? b. Does it m ...

The 'Sending request' message is displayed while loading during a Get request in Postman

When I use the /chat route with the Post method and validate it with a Joi schema, everything works perfectly. However, when I try to send a request using the Get method, it just shows "Sending Request" and keeps on loading. Here is my index.js file: cons ...

Determining the Nearest Date in an Array Using JavaScript

In my array, I store information about each day as an object. For example: {day_year: "2012", day_month: "08", day_number: "03", day_name: "mon"} To enhance the day objects, I have included a timestamp attribute using the following function: function co ...

Can CSS transitions be synced up to happen simultaneously?

Here is a snippet of code showcasing CSS transitions applied to the height property. It seems that CSS transitions work asynchronously, but I am curious if there's a way to make them synchronous without using jQuery or other methods. CSS: .animated ...

AngularJS directive not registering event after model update

Within my angularjs application, I have implemented an element directive that is equipped with an event listener. This listener is designed to respond to a broadcast event from the controller. app.directive('listItem', function(){ return { ...