Using AngularJS to filter an array using the $filter function

Looking for a more elegant way to achieve the following task:

myList.forEach(function(element){
   if (!['state1', 'state2'].contains(element.state)){
     myFilteredList.push(element)
   }
})

I was thinking of using $filter('filter') but I'm not sure how to implement it in this case. Any suggestions would be appreciated.

Thank you

Answer №1

To get an object that does not include state1 and state2, you can use the following code:

myList = [{ state: 'state1', p: 'csss' }, { state: 'state2', p: 'cppss' }, { state: 'state2', p: 'csssss' }, { state: 's1', p: 'csaas' }]
myFilteredList = [];
x = $filter('filter')(myList, (item) => {
    return !['state1', 'state2'].includes(item.state)
})
myFilteredList.push(x)
console.log(myFilteredList);

Answer №2

To filter the list, you can utilize the following code snippet:

myFilteredList = $filter('filter')(myList, function(element){
    return ['state1', 'state2'].indexOf(element.state) == -1
})

angular.module("app", [])
  .controller("ctrl", function($scope, $filter) {
    var myList = [{
        state: 'state1',
        prop: 'prop1'
      },
      {
        state: 'state2',
        prop: 'prop2'
      },
      {
        state: 'state2',
        prop: 'prop3'
      },
      {
        state: 'state3',
        prop: 'prop4'
      },
      {
        state: 'state4',
        prop: 'prop5'
      }
    ]

    $scope.myFilteredList = $filter('filter')(myList, function(element) {
      return ['state1', 'state2'].indexOf(element.state) == -1
    })
  })
<!DOCTYPE html>
<html ng-app="app">

<head>
</head>

<body ng-controller="ctrl">
  <pre>{{ myFilteredList | json }}</pre>
  <script src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
</body>

</html>

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

Replicate the form to a new one while concealing the elements and then submit it

Initially, I was working with just one form. Now, I find myself in a situation where I need to utilize a different form which contains the same inputs. This is necessary because depending on the action taken upon submission, different processes will be tri ...

What is the best way to retrieve the values of various input fields using their numbered IDs and then store them in a MySQL

I attempted to design a form that allows for multiple inserts, where users can add as many titles and languages as they desire by entering a number. The display of titles and languages is functioning correctly, but I am struggling to retrieve the individua ...

Unlock the Power of Sockets in JavaScript and HTML

How can I work with sockets in JavaScript and HTML? Could HTML5 features be helpful? Are there any recommended libraries, tutorials, or blog articles on this topic? ...

Inserting a Specific Iframe into a Designated Location in HTML with the Help of Jquery

Currently, I am encountering an issue with placing a dynamically created iframe inside a specific section of my webpage. The iframe is supposed to be contained within a div element named "maps", but instead it is appearing at the bottom of the page.This ma ...

Updating parent component's scrollHeight of DOM element based on child component in Next.js

I recently encountered an issue with nested accordions. In my project, I have implemented accordions within other accordions, but ran into a problem when the inner accordion expanded and affected the size of the parent accordion. Here's what's ha ...

Can a table with a checkered pattern be created in Ember.js with just Handlebars and ember-composable-helpers?

I'm new to working with Ember.js and I am attempting to create a simple checkered table. In my project, I am utilizing Bootstrap 4, ember-composable-helpers, and Handlebars. Is there anyone who can guide me on achieving this goal WITHOUT the use of ja ...

Deciphering key-value pairs that are separated by commas

I am looking to convert the following format: realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*" Into this JSON object: { realm: "https://api.digitaloce ...

How to resolve a TypeError saying "Object(...) is not a function"?

I've been attempting to display material-ui tabs as a component on another page, but I'm encountering an error that causes the code to break when loading the page with this component. I've tried two different methods of rendering this compo ...

Types of Data Encoded in Base64

Within an application I am developing, there is a feature for downloading files that are stored as Base64 strings. It is essential to correctly pair the data types with the corresponding files in order to ensure successful downloads. I thought I had sorte ...

Cordova Geolocation now displaying incorrect latitude and longitude values as NAN

Recently starting out with javascript and Cordova, I decided to develop a basic GPS app in Visual Studio 2015. The goal was simple: get my current position by clicking on the "CURRENT POSITION" button. Testing it in Firefox yielded positive results. Howev ...

Checking to see if there are a minimum of two checkboxes selected before inputting the data into the database

I am currently using a combination of HTML, PHP, JavaScript, MySQL, and Wampserver. In my project, I have implemented 3 checkboxes where the user can choose a maximum of two options. Once selected, these choices are then inserted into the database. Initi ...

Encountered an npm ERR while executing the React project

I'm encountering an issue with running my React project. When I use the command "npx start", I receive the following error message. Can someone please assist me with this? npm ERR! could not determine executable to run npm ERR! A detailed log of thi ...

What is the method to determine the duration of a video using the FileReader function to access the video file?

My current challenge involves uploading a video to a server and reading it on the client end using `readAsBinaryString()` from FileReader. However, I am facing an issue when trying to determine the duration of this video file. If I attempt to read the fi ...

Consistently encountering the error message "(0 , _reactDom.h) is not a function" or "h is not defined"

I'm currently in the process of developing an app that makes use of electron, react, redux, and several other technologies. At the moment, I have included electron, react, electron-compile, and babel in the project. Redux is installed but has not been ...

The Javascript Image() function fails to load or render

I am currently in the process of developing a basic Sprite class for implementation in a canvas game. However, I am encountering an issue where the image specified during the creation of a new instance of the class does not trigger the onload or onerror ev ...

Exploring the world of JavaScript by dynamically retrieving all class functions

Is there a way to retrieve an array of all functions from a given class, including functions inherited from parent classes? For instance: class Foo extends Bar { funcA() {} } class Bar { funcB() {} } const instanceFoo = new Foo(); getClass ...

Error: The function exec in matchExpr[type] is not defined

I made some changes to Object.prototype and now I'm running into errors with jQuery's methods on selectors. The error message I'm getting is: Uncaught TypeError: matchExpr[type].exec is not a function Additionally, when trying to use $.po ...

Update the state within a different function in Vue.js

Just starting out with Vue.js and I'm trying to figure out how to update the component's state from a function in another file. I have a basic form with only an input file element. Once the user selects a file, the onChange handler will be trigg ...

Converting RSS title to HTML format with the help of JavaScript

I am currently working on populating a menu on a webpage with the 5 latest topics from our site's RSS newsfeed using JavaScript (specifically jQuery version 1.9.1). I have been searching for a solution, but most answers I find reference deprecated scr ...

Upon the second click, the addEventListener function is triggered

When using the window.addEventListener, I am encountering an issue where it only triggers on the second click. This is happening after I initially click on the li element to view the task information, and then click on the delete button which fires the eve ...