How to Find and Count Duplicate Values in an Array using AngularJS

My form consists of 5 questions, each with 3 different answers to choose from.

For example: q1. What is your favorite color?

Radio button-1: blue Radio button-2: red Radio button-3: grey

While most questions offer the same values (blue, red, grey), I am looking to calculate the total count of each value selected at the end of the form in order to determine if the respondent aligns with any of these values (blue, red, or grey).

I am developing this form using angularjs and here is my current progress:

<label>Q1. What is your favorite color?</label>
    <div class="form-group">
        <div class="radio">
            <label>
                <input type="radio" ng-model="formData.color" value="blue">
                Blue
            </label>
        </div>
        <div class="radio">
            <label>
                <input type="radio" ng-model="formData.color" value="red">
                Red
            </label>
        </div>
        <div class="radio">
            <label>
                <input type="radio" ng-model="formData.color" value="grey">
                Grey
            </label>
        </div>

This portion of code only functions correctly if the values are already stored in the variable.

$scope.formData = { };
$scope.formData = [];
$scope.formData.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < $scope.formData.length; i++) {
    if ($scope.formData[i] != current) {
        if (cnt > 0) {
            console.log(current + ' appears ' + cnt + ' times');
        }
        current = $scope.formData[i];
        cnt = 1;
    } else {
        cnt++;
    }
}
if (cnt > 0) {
   console.log(current + ' appears ' + cnt + ' times');
}

Answer №1

Below is an example solution plunker. Do you think it will be effective?

controller

  $scope.questions = [
    'Q1. What's your favorite movie genre?',
    'Q2. Which movie would you watch multiple times?',
    'Q3. What type of movie do you enjoy the most?'
  ];
  $scope.formData = [];

  $scope.stats = function() {
    $scope.results = {};
    for (var i = 0; i < $scope.formData.length; i++) {
      var genre = $scope.formData[i];
      if(genre) {
        if ($scope.results.hasOwnProperty(genre)) {
          $scope.results[genre]++;
        } else {
          $scope.results[genre] = 1;
        }
      }
    }
  };

template

<div class="form-group" ng-repeat="q in questions">
  <label>{{q}}</label>
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData[$index]" value="action">Action
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData[$index]" value="comedy">Comedy
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData[$index]" value="drama">Drama
    </label>
  </div>
</div>

<button ng-click="stats()">show results</button>

<ul>
<li ng-repeat="(g, n) in results"> {{g}} appears {{n}} times</li>
</ul>

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

Display the table once the radio button has been selected

Before we proceed, please take a look at the following two images: image 1 image 2 I have over 20 fields similar to 'Image 1'. If "Yes" is selected, then a table like in 'Image 2' should be displayed. This means I have 20 Yes/No fields ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

When the window size is reduced, the navigation vanishes

Whenever I resize the window, the navigation bar disappears. Here is the image of the page before resizing the window https://i.sstatic.net/UiRB9.png Below is the image after resizing the window https://i.sstatic.net/X00d2.png Displayed below is the cod ...

Strange response received from $http GET request on Android device running Crosswalk

I am attempting to retrieve data in JSON format from an API using AngularJS. The process is successful on iOS and desktop browsers, but I'm encountering a strange response when trying it on my Android device. The request code looks like this: $http({ ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

I am having trouble specifying a class within an SVG using D3.js

I have been facing a strange issue with my script. When I try to execute the following code: var key="#US" d3.select(key).style("fill", "red"); it seems like it's not working for me. Interestingly, when I run the same co ...

Inadvertent scroll actions causing unexpected value changes in Material UI sliders

I am currently working on a React application that utilizes Material UI, with slider components integrated throughout the interface. However, I have encountered an issue when using a touch screen device - unintentional changes to the slider values occur wh ...

Error thrown when attempting to access properties of null values (Uncaught TypeError: Cannot read properties of undefined (reading 'map'))

import React, { useState, useEffect } from "react"; import { TaskLists } from "./TaskLists"; import { Daycard } from "./daycard"; import { getTasks, deleteTask } from "../api/task.api"; export function TaskManager() { const [tasks, setTasks] = useState( ...

Is it possible to leverage the flex features of react-native in a manner similar to the row/column system of

Is it a good idea to utilize flex in react native by creating custom components that retrieve flex values? I previously used the bootstrap grid system and now I am exploring react native. Is there a way to implement this example using react-native bootstr ...

What is the best approach for managing multiple HTTP requests in my specific situation?

I have a query about handling multiple HTTP requests in my code to ultimately get the desired result. Here is an outline of my approach: var customer[]; var url = '/api/project/getCustomer'; getProject(url) .then(function(data){ ...

Using Angular with a hapi.js server that supports JSONP data requests

In my project, there is an endpoint specifically set at /api/profile that accepts post parameters. var http = require('http'); var serverConfig = require('../server.config.js'); var request = require('request'); module.expo ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...

What's preventing the mobx @computed value from being used?

Issue: The computed value is not updating accordingly when the observable it is referencing goes through a change. import {observable,computed,action} from 'mobx'; export default class anObject { // THESE WRITTEN CHARACTERISTICS ARE COMPUL ...

Fetching JSON data using Javascript/JQuery

My goal is to access JSON data from an online web service that queries a MySQL database for a specific string and use Javascript to present it on an HTML page. My challenge lies in effectively displaying the retrieved information. The relevant part of my ...

What are the benefits of refraining from calling functions in AngularJS views to showcase data in a more objective manner?

In our work application, we have a function that generates various objects inheriting methods from a prototype. To summarize, this function creates instances of the MileCounter object. Here is an example: function MileCounter(totalMilesRan, numOfDaysToRu ...

The route is redirecting to an incorrect destination

Whenever a button is clicked on my webpage, this particular function is triggered. $scope.go=function(takenAt){ var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParam ...

Struggling with developing a chrome extension

I have successfully developed a Chrome extension that, when clicked, says hello world. However, I am facing an issue with creating a simple button that triggers an alert when pressed. Could it be due to the inclusion of JavaScript in an HTML extension file ...

Three.js Ellipse Curve Rotation

Purpose My goal is to create an EllipseCurve () where a camera will move. The Approach I Took to Achieve the Goal Below is the code snippet for creating the ellipse: var curve = new THREE.EllipseCurve( 0, 0, 1, 1, 0, 2 * Math.PI, false, ...

Facing an issue with sending data in AJAX Post request to Django View

I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...