Ways to refine data using multiple criteria

I have a list of alarm data that I need to filter based on specific conditions. If there are multiple alarms of type "pull_Alarm" and "emergency_alarm" in the same location, I want to prioritize the "emergency_alarm".

Here is my list:
    [
        {
            alarmType:"Normal_ALARM"
            location:"Ward5"
            severity:"URGENT"
        },
        {
            alarmType:"Emergency_Alarm
            location:"Ward1"
            severity:"URGENT"
        },
        {
            alarmType:"PULL_Alarm"
            location:"Ward1"
            severity:"NORMAL"
        }
    ]
    

The desired filtered list should look like this:

[
      {
        alarmType:"Normal_ALARM"
        location:"Ward5"
        severity:"URGENT"
      },
      {
        alarmType:"Emergency_Alarm
        location:"Ward1"
        severity:"URGENT"
      }
    ]
    

If anyone has any suggestions on how to apply these filters, please let me know.

Answer №1

Implement a filter using switch cases or if-else conditions.

.filter("alarmFilter", function () {
    // Specify the desired condition here
});

Then, use this filter in your expression to apply the specified condition.

Answer №2

Create a custom filter

$scope.filter1 = function(item)
    {
        return (item.severity == 'URGENT');
    };

Implement the custom filter

<div ng-repeat="item in object| filter:filter1">{{item.alarmType}}</div>

Check it out on JSFIDDLE http://jsfiddle.net/Lvc0u55v/8866/

Answer №3

To customize the filtering process, follow the steps outlined below.

angular.module('myFilters', []).
filter('byAlarmCount', function() {
  return function(alarms, severity) {
    var items = {
      severity: severity,
      out = []
    };
    angular.forEach(alarms, function(v, k)) {
        if (this.severity[v.severity] === true) {
          this.out.push(v);
        }
    }
    return items.out;
  }
});

The DOM structure is as follows:

<ul>
    <li ng-repeat="alarm in list | byAlarmCount:severityFilter">{{alarm.location}: {{alarm.alarmType}}</li>
</ul>

Answer №4

If you are in need of performing intricate filtering tasks, it is advisable to explore third-party JavaScript libraries such as lodash (https://lodash.com/) or Underscore (http://underscorejs.org/).

These libraries offer a multitude of tools that can assist with filtering, mapping, and various other commonly used utility operations.

For instance, in the current context, you could utilize _.where / _.filter from underscorejs.

var filteredData = _.where(<YOUR DATA SOURCE>, { property: VALUE, ...});

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

Can Express POST / GET handlers accommodate the use of jQuery?

I created a simple Express server to retrieve data from an HTML form and make queries to OpenWeatherMap using that data: const { OpenWeatherAPI } = require("openweather-api-node"); const express = require("express"); const bodyParser = ...

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...

Adjusting an image size using JQuery after resizing a canvas will only resize the image itself, not

How can I resize an image within a canvas using JQuery in a way that only the image is resized, not the entire canvas? function resizeImage(width, height){ var image = document.getElementById('resizeImage'), canvas = document.createEleme ...

Obtain asynchronous state in VueJS without the need for intricate v-if conditions

I am working on an application that heavily relies on Vue-Router and Vuex for state management. Within the Dashboard component, important user information is displayed. This data is fetched asynchronously from a database by Vue and then stored in Vuex. T ...

What is the process for implementing optional chaining on a JSON object?

I'm currently facing an issue where I need to compare a value within a JSON object with a variable. if (resp.userdetails.name == username) { // do something } The challenge arises when not all resp objects contain the userdetails property, resulting ...

Issues with sending data using ajax

Trying to get weinre working through Ajax by calling this on dom ready: $.ajax({ url: 'http://debug.build.phonegap.com/target/target-script-min.js#hutber', dataType: "script", crossDomain: true, error: function(data){ c( ...

Annoying animation triggered upon loading of the page using AngularJS

I'm encountering an issue with a webpage element that has a hide/show animation. Despite the initial state being hidden, when the page loads, it still displays the hide animation. I attempted to set ng-show="false", but the hide animation persists upo ...

The issue of batch-wise data clustering on Google Maps when zooming in or out

//The code snippet provided below initializes a map with specified settings and clusters markers based on the data sent in patches of 10000.// var mapDiv = document.getElementById('newmap'); map = new google.maps.Map(mapDiv, { center ...

The compatibility between Node JS and Vue JS front-end seems to be glitchy and

I am currently developing a Node JS backend application and Vue JS front-end. In order to authenticate users, I need to implement sessions in the API. For my backend server, I am using the following components: express (4.18.2) express-session (1.17.3) c ...

Issue with PHP functionality not functioning properly

I've been working on implementing an AJAX Form to allow users to upload their profile picture on my website. However, I've encountered some difficulties with the process. I have created a PHP page where the form is supposed to be posted using AJA ...

What is the preferred method for initiating a call from a JSP to a servlet using an href link?

Currently, I am successfully using href to call a servlet URL. However, I would like to add parameters and receive a response from this request. Is it possible to achieve this? I attempted an AJAX call but encountered a CORS issue when trying to call an ex ...

How can one achieve the equivalent of Flask Safe when making an ajax call?

Having trouble replicating equivalent functions in my Ajax call as I can in regular Javascript on my main HTML page. Using Python/Flask at the back-end. Any similar methods to use the {{ variable | safe }} syntax in AJAX for similar results? My code snipp ...

Retrieve data from a local JSON file and showcase it in a list within a Next.js project. The error "Property 'data' does not exist on type String

Having trouble displaying the names of crates (which are filled with records/albums) from a local JSON file. The names aren't showing up and I'm wondering if I should be using params or if perhaps not stringifying the JSON would help. Visual Stud ...

Difficulties arising when trying to convert latitude and longitude coordinates to xyz for camera rotation within Three.js

Currently, I am working on a JavaScript application that allows users to design their own closet. My goal is to enable smooth rotation of the closet without changing the distance from the camera to the closet. While it would be simple to rotate the object ...

How can I ensure that TypeORM, Type GraphQL, Apollo Server, and Azure Functions work together seamlessly?

I have an Azure Function written in TypeScript that utilizes various technologies such as TypeORM, Apollo Server, and TypeGraphQL. The function involves creating resolvers for projects and tasks and establishing a database connection. import { createConne ...

Error: The `ngMetadataName` property cannot be accessed because it is undefined or null in Internet Explorer version 10

Encountered an issue in IE 10 that is not present in IE 11: Error: TypeError: Unable to get property 'ngMetadataName' of undefined or null reference The property ngMetadataName can be found in the file vendor.js. This is the content of polyf ...

Updating React props using useState?

Below is a component that aims to enable users to update the opening times of a store. The original opening times are passed as a prop, and state is created using these props for initial state. The goal is to use the new state for submitting changes, while ...

Vue Pinia ensures that reactive state is only updated once, preventing unnecessary updates

In my Vue application, the structure is as follows: App.vue -GroupWrapper --GroupListing -PeopleWrapper --PeopleListing -ConversationWrapper Within my user store that utilizes Pinia, I primarily call user.findChats() in the App.vue component. Code snippe ...

Keep sending HTTP requests until the header contains an attachment

Welcome to our web application where you can generate and download a .zip file simply by visiting the URL. I am looking to develop a Node.js application using the requestjs library that will continuously send requests until it detects an attachment header ...

Transforming the button behavior with jQuery

I have encountered a situation where I am working with code in Twig. {% if followsId == null %} <div id="followUser" class="follow" data-userId="{{ profileUserData.id }}" data-currentUserId="{{ loggedUserData.id }}" data-action="follow"> ...