Breaking up an array in AngularJS based on object outcomes

My array consists of objects structured like this:

{
  __v: 0,
  _id: "5835ced6ffb2476119a597b9",
  castvote: 1,
  time: "2016-11-23T17:16:06.676Z",
  userid: "57e0fa234f243f0710043f8f"
}

I am looking to create new arrays that filter these objects based on the castvote values - one for objects where castvote is set as 1, and another for those with a castvote value of 2.

Answer №1

To achieve this functionality in the controller, utilize the $filter feature.

$scope.castvoteOne = $filter('filter')($scope.results, {castvote: 1});
$scope.castvoteTwo = $filter('filter')($scope.results, {castvote: 2});

Check out the DEMO here

Answer №2

To achieve this grouping, employ the Array.prototype.reduce function along with a hash table. This will help organize the array into an object where the key represents the castvote, and the value contains the elements associated with that specific castvote.

You can then access the result for a particular castvote by using result[castvote]

Check out the demo provided below:

var array=[{__v:0,_id:"5835ced6ffb2476119a597b9",castvote:1,time:"2016-11-23T17:16:06.676Z",userid:"57e0fa234f243f0710043f8f"},{__v:0,_id:"5835ced6ffb2476119a597b9",castvote:2,time:"2016-11-23T17:16:06.676Z",userid:"57e0fa234f243f0710043f8f"},{__v:0,_id:"5835ced6ffb2476119a597b9",castvote:1,time:"2016-11-23T17:16:06.676Z",userid:"57e0fa234f243f0710043f8f"}]

var result = array.reduce(function(hash){
  return function(p,c) {
    if(!hash[c.castvote]) {
      hash[c.castvote] = [];
      p[c.castvote] = hash[c.castvote];
    }
    hash[c.castvote].push(c);
    return p;
  };
}(Object.create(null)),{});

// use result[castvote] to get the result for that castvote
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

Answer №3

In accordance with the recommendations made here

One option is to utilize Underscore's groupby function to categorize items based on a specific property.

_.groupBy($scope.results, "castvote")

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

There seems to be an issue with a potentially null object in an Angular project while trying to view a PDF file

IDENTIFY THE ERROR: printContents = document.getElementById('print').innerHTML.toString(); ON LINE 4: print(): void { let printContents!: string; let popupWin!: any; printContents = document.getElementById('print').innerHTM ...

Issue with reading initial state value in React application

I'm currently working on an application centered around payment recording functionality. Within my app, there is a state structure that looks something like this: const [state, setstate] = useState({ amountPaid: Number(bill.total), // the 'b ...

My Node.js environment is unable to recognize the Express object, causing issues with setting paths for my CSS and JavaScript files

Check out the following link for more information: http://expressjs.com/en/starter/static-files.html I'm currently utilizing sockets.io: const PORT = 3000; var objServer = require('express')(); var http = require('http').Server(o ...

Navigating a Frame and Clicking a Link with Puppeteer: A Step-by-Step Guide

I am facing an issue with clicking on an anchor link within a page that is supposed to open a new tab for exporting a PDF. The problem arises because this link is located inside a frame within a frameset structure as shown below: https://i.stack.imgur.com ...

retrieving a two-dimensional array without prior knowledge of its dimensions

As a beginner in utilizing pointers, I'm encountering an issue. I need to receive a 2D array of characters from the user, along with the number of rows and columns, and the specific content to fill the array with. int rows, col, i, j; char ** ...

Display loading images using the Bxslider plugin

Currently, I have implemented a Bxslider on my website with the following HTML markup: <div class="slide"> <a target="_blank" href="#"><img src="image.jpg"/></a> </div> <div class="slide"> <a target="_blank" href= ...

Retrieve the value of a related object based on the user's click

Check out this sample code on JSFiddle <a href="#"></a> <a href="#"></a> <a href="#"></a> <a href="#"></a> <div></div> JavaScript: function Product(name, price){ this.name = name; this. ...

emailProtected pre-publish: Running `python build.py && webpack` command

i am currently using scratch-blocks through the Linux terminal I have encountered a problem which involves running the following command: python build.py && webpack [email protected] prepublish: python build.py && webpack Can anyon ...

Fetching information using JSON for creating a RangeArea Chart with CanvasJS

I'm currently working on creating a range area chart with CanvasJS and PHP to fetch data from a database. After setting up the php script to retrieve values from the DB, here's what I have: <?php header('Content-Type: application/json&a ...

Unable to recognize click event within the ng-click function

I need to identify when a click event occurs on an SVG element, specifically on a g element within the SVG element. Currently, I have created this JSFiddle The ng-click function is working properly, but unfortunately, the click event is not being detecte ...

Is it possible to create a route in AngularJS that displays multiple views at once?

Imagine a scenario in which we have a specific route, let's call it myapp\profile, with two different modes (buyer/seller). Here is what I am aiming to accomplish: Maintain the same route URL for both modes. Switch between views using different ...

JavaScript Toggle Visibility on Click

Click to reveal a new div <div id="box1">abc</div> <div id="box2" style="display:none;">awklnnbc</div> <div id="box3" style="display:none;">wgweilwe</div> <div id="box4" style="display:non ...

Node.js not receiving expected Ajax response

Why is my Ajax request not receiving the proper response? It always shows readyState '4' with a response status of '0'. What could be causing this issue? Client-Side Code: var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = f ...

Exploring ways to customize the input of primary key and _id in mongoose to be optional

I am looking to create a primary key in MongoDB that does not require user input, but is automatically generated. I have tried using {type: ObjectId, required: false}, but it did not work because I left the primary key empty. Is there another way to make t ...

Adding an operation to a function that is linked to an event

On one of my pages, I have a button that triggers some ajax calls with data binding. The binding code is generic and used in various parts of the application, so altering its behavior could impact other users. However, I now have a specific requirement fo ...

Extract the value of an HTML tag and store it in a PHP variable

I have successfully implemented JavaScript code to dynamically update the value of an input tag in my popup. However, when I try to echo out this updated value using a PHP variable within the same popup, it doesn't seem to work as expected. Despite un ...

Optimizing Jquery for dynamically generating large tables

Looking to create a massive table using a Java servlet and sending it to the client as an AJAX response. The table cells have specific styles: <td style="background-color:blue;border-color:yellow;" onClick=tableClick(this)>value1</td> <td s ...

Reduxforms does not rely on preloaded CSS or JavaScript

Currently, I am utilizing MDBootstrap as my primary CSS framework and integrating redux forms to simplify form management. The issue at hand is that the design and style of elements appear different compared to the original static html page layout. Here ...

The Vue component does not render the JS Promise and instead displays it as

After setting up a promise that will be returned once a correct event is called with the correct action, I have the following code: import {EventBus} from "./EventBus"; export function completed() { EventBus.$on('queue-action', e => { ...

Steps to deactivate an HTML submission button once it has been clicked

I have encountered an issue while working on a signup page using PHP and JavaScript. After the user clicks the "submit" button, the page begins to load before redirecting. If the user clicks "submit" again, an error occurs because the data has already been ...