Using a custom AngularJS filter within an ng-repeat loop

I am attempting to retrieve distinct values from a JSON response using a personalized filter.

data:

[
{
    "SHFUserID": "400",
    "AlertID": "12",
    "TickerID": "4512",
    "Ticker": "GOOG",
    "Active": "1",
    "Status": "2"
},
{
    "SHFUserID": "400",
    "AlertID": null,
    "TickerID": "4512",
    "Ticker": "GOOG",
    "Active": null,
    "Status": null
},
{
    "SHFUserID": "400",
    "AlertID": null,
    "TickerID": "10190",
    "Ticker": "IBM",
    "Active": null,
    "Status": null
}
]

filter:

.filter('uniqueTickers', function() {
return function(tickers) {
    var tags = {};
    angular.forEach(tickers, function(obj) {

      if(!(obj.Ticker in tags)){
        tags[obj.Ticker] = {id: obj.TickerID, name:obj.Ticker}

        if(!tags[obj.Ticker].pending){
          tags[obj.Ticker].pending = 0;
        }
        if(!tags[obj.Ticker].settled){
          tags[obj.Ticker].settled = 0;
        }
        if(!tags[obj.Ticker].order){
          tags[obj.Ticker].order = 3;
        }
      }
  if(obj.Status === "1"){
    tags[obj.Ticker].pending = 1;
    if(tags[obj.Ticker].order > 2){
      tags[obj.Ticker].order = 2;
    }
  }
  if(obj.Status === "2"){
    tags[obj.Ticker].settled = 1;
    if(tags[obj.Ticker].order > 1){
      tags[obj.Ticker].order = 1;
    }
  };
    });
return tags;
};

html:

 Search: <input ng-model="query">
  Sort by:
  <select ng-model="orderProp">
    <option value="name">Alphabetical</option>
    <option value="order">Alert Status</option>
  </select>
  <ul class="tickerList">
    <li ng-repeat="ticker in tickers | filter:query | orderBy:orderProp | uniqueTickers">
      <a href="#/ticker/{{ticker.id}}">{{ticker.name}}</a>
      <p>{{ticker}}</p>
    </li>
  </ul>

but the output appears as:

GOOG
{"id":"4512","name":"GOOG","pending":0,"settled":0,"order":3}

IBM
{"id":"10190","name":"IBM","pending":0,"settled":0,"order":3}

instead of:

GOOG
{"id":"4512","name":"GOOG","pending":0,"settled":1,"order":1}

IBM
{"id":"10190","name":"IBM","pending":0,"settled":0,"order":3}

The objective is to maintain uniqueness in the result set while marking "pending" or "settled" as true if any of the records for that ticker are pending or settled.

Answer №1

Following a thorough discussion, the solution came in the form of preventing the overwrite of existing data by incorporating a conditional check around the initial section of code as shown below:

if(!(obj.Ticker in tags)){
    tags[obj.Ticker] = {id: obj.TickerID, name:obj.Ticker};

    if(!tags[obj.Ticker].pending){
      tags[obj.Ticker].pending = 0;
    }
    if(!tags[obj.Ticker].settled){
      tags[obj.Ticker].settled = 0;
    }
    if(!tags[obj.Ticker].order){
      tags[obj.Ticker].order = 3;
    }
}

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

Having difficulty getting AJAX requests or session management to work properly

I have a service that is very similar to the one discussed in this thread: Php: Form auto-fill using $_SESSION variables with multiple php files I wanted to ask my question there, but I don't have enough reputation points. So, I'm posting a new ...

Encountering the following issue: angular.js:38Uncaught Error: [$injector:modulerr]

I'm struggling to resolve this issue and need help! I have tried several solutions but none of them seem to work. I attempted to debug the AngularJS application, but I am unsure how to do so. Could this be a loading issue or something else entirely? ...

Ensure the browser back button navigates to the login page seamlessly, without displaying any error

A scenario I am working on involves a Login jsp that accepts a user email and sends it to a servlet. If the provided email is not found in the database, the servlet redirects back to Login.jsp with an attribute "error". Within the header of Login.jsp, ther ...

Accelerate the window.onload process

As a newcomer to javascript and Jquery, I am working with javascript code that generates a table of content based on <h2> and <h3> tags. However, I have noticed that it is running slow as it waits for the entire page to render. I attempted to ...

Generate an HTML table by utilizing deeply nested JSON information

I am struggling with creating an HTML table from a dynamic nested JSON data structure. Despite my limited knowledge of data manipulation, I attempted various methods without success. The required data is missing in the output. JSON data... https://i.ss ...

Tips and tricks for implementing pagination with jquery and jsp

I have a JSP page where I am displaying records fetched from an Oracle database. However, I want to show only a limited number of records at a time and implement pagination using jQuery and JSP. My goal is to display 1-10 records initially, and upon clic ...

Exploring how to browse and dynamically assign image sources with JavaScript/jQuery in an Asp.net mvc 4 framework

On my .cshtml page, I have an <img/> tag. <img id="ImageID" alt="" width="100%" height="100%" /> I want to dynamically set the src attribute by selecting the image file path using a file control. Although I attempted the following code in my ...

Using ng-repeat with an AJAX-called JSON is not possible

I've been struggling with handling JSON data from an AJAX call and displaying it using ng-repeat. If you want to take a look at my code in a more organized way, I've shared it on http://jsfiddle.net/7quj9omw/. However, please note that the code ...

Repurposing components like custom text inputs, spans, and more in ASP.NET MVC using Razor

Our team is currently working on a website project where we keep re-using components repeatedly. One particular instance involves a span that functions as a warning light. It's accompanied by some C# code with properties for color and text, Javascript ...

Utilizing setTimeout within every iteration is ineffective

A vast gallery containing around 400 pictures is featured on my website. I have implemented a button that allows users to delete all images from both the DOM and the server through an AJAX request for each file. While testing, I attempted to use the setTi ...

What steps can I take to improve the efficiency of this filtering process in Vue.js?

I am seeking ways to enhance the method I utilize for determining which values should be displayed in a table. At present, my table displays various values and is accompanied by input fields. The values chosen in these input fields serve as filters for the ...

Indeed, verification of an array - values are mandatory only when the array exceeds a length of 1

In my form, each row contains 2 dropdowns and I have the ability to dynamically add or remove rows except for the first one. My goal is to allow form submission only if there is one pre-rendered empty row, otherwise the form should not be able to submit if ...

Sending data using the $http service and handling asynchronous operations with

Consider the code snippet below: function callAPI() { return $http({ method: "POST", url: "http://destined/to/fail", data: {param1: 1}) .success(function(data, status) { return { test: "success!";} } ) ...

Differences between Selenium WebElement.click() and triggering a click event using Javascript

I am curious about the distinctions between utilizing the click() method of the WebElement and locating the element by id to trigger the click event with JavaScript. To clarify, the first approach involves calling the .click() on an instance of WebElement ...

Tips for loading HTML content before executing any JavaScript code or requesting user input via prompt

I am looking to have the page function in a specific way: The HTML loads, and the first prompt asks the user for input. Once the prompt is submitted, the running total changes and is displayed on the page. The same process happens for the second prompt and ...

React Board not updating Cell Component

Edit After making changes to line 106 by adding setCellsSelected, I finally managed to trigger cell re-rendering. The functionality was baffling at first, React can be quite perplexing. Summary My current project involves visualizing depth-first search i ...

Tips for creating canvas drawings in GWT

Here's a simple jQuery code to draw a triangle in a canvas element that is 40 by 40: var context1 = $("#arrow_left").get(0).getContext('2d'); context1.beginPath(); context1.moveTo(25,0); context1.lineTo(0,20); context1.lineTo(25,40); contex ...

The response from unirest in node.js came back as undefined

Currently, I am diving into the world of Facebook bots, despite not being well-versed in node.js development. Stepping out of my comfort zone and embracing this new challenge for the first time has been quite exhilarating. Below is the function that I hav ...

Decoding the Language of HTTP Status Codes

Let's imagine a scenario where I create a file called api.js: const {somefunction} = require('../controllers/some-controller'); app.get('/data/', somefunction); In my some-controller.js: exports.somefunction = async (req, res,next ...

managing the AJAX server's response

Struggling with a seemingly simple project where a button click should display a random saying generated from PHP, I don't have access to the PHP code and feel a bit lost. The issue seems to be in how I'm handling the server response (the handleS ...