Determine the frequency of occurrences for each item within an array

Here is the code snippet I created:

<html> 
    <head>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
            <link href="app.css" rel="stylesheet" type="text/css"/>
            <title>TNF FANTASY</title>
    </head>
    <body>
        <div class="app" ng-app="myApp" ng-controller="myCtrl">
            <div class="total">
                <i><h4>Money Remaining: <br>{{total |currency}}</h4></i> <h4>{{playersSelected}}</h4>
            </div>

            <ul>  
                <li class="players" ng-repeat="player in players">
                    {{player.name}} <br> 
                    {{player.Team}} <br> 
                    {{player.price| currency}} <br>
                    {{player.position| uppercase }}
                    <br>
                    <button ng-click="buy($index)">buy</button>
                </li>
                </ul>
        </div>

        <script>
            var app = angular.module('myApp', []);
            app.controller('myCtrl', function($scope) {
            $scope.playersSelected = "0/6";
            $scope.total = 50000000;

            // keep track of what was bought already
            $scope.history = [];
            $scope.denteries = [];
            $scope.players = [
              {name : "Yasin 'YB' Amusan", Team : "Industry", price: 8000000, position: 'forward', image: src='http://res.cloudinary.com/deji/image/upload/v1489787662/blank_photo_mqvivv.png'}...

             $scope.buy = function(i) {
                var p = $scope.history.indexOf(i);

                if (p !== -1) { 
                    $scope.history.splice(p, 1);
                    $scope.total += $scope.players[i].price;
                    $scope.playersSelected = $scope.history.length + "/6";
                } else { 
                    if ($scope.total < $scope.players[i].price) {
                        return;
                    }
                    $scope.history.push(i);
                    $scope.total -= $scope.players[i].price;
                    $scope.playersSelected = $scope.history.length + "/6";
                }
            };
          });
        </script>
    </body>
</html>

I have a requirement where users can only buy specific positions: two "defenders" or "hybrids", two "midfielders" or "hybrids" and two "forwards" or "hybrids". This should total 6 players to buy.

I've attempted to use AngularJS' indexOf method but it's not giving the desired results. Is there a way to implement this functionality within AngularJS or is it too complex?

Answer №1

If you're looking to count occurrences in an array, you can create a helper function like this:

function countOccurrences(arr, target) {
    let count = 0;
    for (let i in arr) {
        if (arr[i] === target) {
            count++;
        }
    }
    return count;
}

UPDATE:

After receiving feedback in the comments, I realized the initial code provided may not be sufficient. Let's modify the function to this:

function countOccurrences(players, arr, target, helper) {
    let count = 0;
    for (let i in arr) {
        if (((typeof helper === "function") && (helper(players, arr[i], target))) || ((typeof helper !== "function") && (arr[i] === target))) {
            count++;
        }
    }
    return count;
}

A helper function is needed for this like so:

function myCustomHelper(players, value, target) {
    return players[value] && (players[value].position === target);
}

Then, you can call the function like this:

countOccurrences($scope.players, $scope.history, "defender", myCustomHelper);

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

Ensure to verify the presence of a null value within the ngFor iteration

I have a webpage where I am displaying information in buttons. These buttons show various objects from a list along with their corresponding fields (e.g. object.name, object.age, etc.). Sometimes, one of those fields is null. How can I check if a value is ...

I'm experimenting with crafting a new color scheme using MUI, which will dynamically alter the background color of my card based on the API

I am attempting to create a function that will change the colors based on the type of Pokemon. However, I'm not sure how to go about it. Any suggestions or ideas!? Check out where I'm brainstorming this logic [This is where the color palette sh ...

Are there any instances where CSS is overlooking certain HTML elements?

In the following HTML code snippet, the presence of the element with class ChildBar is optional: <div class="Parent"> <div class="ChildFoo"></div> <div class="ChildBar"></div> <!-- May ...

The functionality of cropping is not supported within a Bootstrap modal

I have been using ngimgcrop successfully to crop images within my application. However, I encountered an issue when trying to display the cropped images inside a uibmodal (AngularJS modal). Despite trying various solutions, such as using ng-init, I was una ...

Vue - Syntax error: Unexpected token, expecting "}."

I recently started working with Vue and have encountered a simple component issue. Sometimes, when I run npm run serve or save a file that is already being served, I receive the following error message: E:\Development\website\app>npm run ...

What is the correct location for the webpack.config.js file within a React project?

I recently inherited a React project that I need to continue working on, but I have never used React before. I've been advised to use a web worker in the project and have found a tool that seems suitable for my needs: Worker Loader The suggested meth ...

AngularJS - Make Checkbox Checked When Value is True

Here is a user json object data: var users = [ { firstName: 'Sven', lastName: 'Butzbak', userID: '1', // TODO refactor to _id gender: 'male', a ...

Ways to retrieve information and functions from defineExpose in Vue

`I am attempting to call a method from a child component within the parent component in Vue using the composition API. I have defined the method inside defineExpose, but I am unable to access it in the parent component. Hero.vue (ChildComponent) <templ ...

Should I use one or two containers for my Dockerized Angular app?

Understanding how an Angular app works in Docker can be challenging. Angular requires a web server like nginx to run, as well as nodejs to access the backend. Should these be separated into two containers, or is there another way to handle this? Currently ...

The userName data is not being displayed in the console.log when using socket.io

I'm currently in the process of developing a chat application using socket.io. My goal is to log the user's name when they join the chat. I have set up a prompt on the client side to capture the user's input and emit it to the server. Howeve ...

I discovered that the chips' content was in need of updating once I selected the content from the menu

I want to create a chips feature similar to Google Flights where clicking on the chips opens a menu. Currently, when I click on the chips, the menu opens up and 'Sports' is displayed as a chip. However, I want to update the 'Sports' tex ...

What is the best way to transfer my object along with its unique textures from Blender to ThreeJS?

I've been using the STL Loader in three.js to import objects from Blender, but I'm facing an issue where the textures are not appearing. I suspect it has something to do with the MeshBasicMaterial of the object. I attempted to switch it to Phong ...

Obtaining information from a intricate string input

{JSON.stringify(walletData.transactions, null, 2)} My goal is to extract backend data and display it as a table. The response has been converted into an array as shown below. [ { "date": "Nov 07, 2023", "description" ...

Error: Unable to locate the tslint command

After attempting to utilize tslint --fix, I encountered the error message bash: tslint: command not found.... To install tslint, I ran the following command: yarn global add tslint typescript. The operating system on my machine is Centos 7. ...

Is there a way to split a string into words using arrays and functions?

The code I am currently working on is as follows: function look(str) { var stringArr = ['JAVA']; var arr = []; var novaString = '' for(i = 0; i < stringArr.length; i++) { arr = stringArr; } console.log(arr) return ...

Tips for setting a char value to a constant char pointer

Is there a way to assign a char to a const char* in the C programming language? const char* cp; unsigned maxlen = 20; cp = new char[maxlen]; char p = 'U'; cp = p; Encountering the following error: Error: invalid conversion from 'char&apos ...

When using express and passport-local, the function `req.isAuthenticated()` will typically return a

I'm seeking some insight into my current situation. I've noticed that whenever I call req.isAuthenticated() in an app.router endpoint, running on port 3001 via the fetch API, it always returns false. It seems like the connect.sid is not being pro ...

Hoping for a swift ajax response from the identical function

Even though similar questions have been asked multiple times, I have gone through many of them and still haven't found a solution to my specific issue. I am currently using a Wizard Jquery Plugin that triggers a function onLeaveAStepFunction when a s ...

Executing a command upon the pressing of the enter key within a text input field

Here is my input field: <input type="text" id="word" /> I am looking for a JavaScript function that will be triggered when the user hits enter in this text box. I searched for an answer but couldn't find one that fits my spe ...

Error Encountered: Module Not Located

I am encountering an error in my Project where it keeps showing 'Cannot find module' even after numerous attempts to install and uninstall packages simultaneously. The problem persists, and I can't seem to resolve it. https://i.sstatic.net/Z ...