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

Having trouble setting $scope after redirecting to a partial template via routing

Looking to create a website that loads all necessary templates upon the initial visit. Currently, I only have one partial template but plan to add more in the future. Despite having just this one template, I'm struggling with binding the data from my ...

Looking for guidance on writing a JASMINE test case for my method. I've been struggling to mock the event listener. Can you please direct me to a relevant link or share some mock examples

Looking to create a jasmine test for the code snippet below... refreshCacheIfNewVersionIsAvailable(); //Function to check for a new cache version on page load and refresh the app cache if newer files are available function refreshCacheIfNewVersionIsAvail ...

Having trouble with Laravel 5.5 and ajax file uploads?

I am encountering an issue with Laravel 5.5 while trying to get an ajax file. I can successfully receive the file using $_FILES, but $request->file() is not working as expected. Here is the code in question. Below are the HTML & Ajax elements: <html&g ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

Below are the steps to handle incorrect input after receiving only one letter:

H-I This is my input .centered-name { width: 80%; margin: auto; } .group { width: 100%; overflow: hidden; position: relative; } .label { position: absolute; top: 40px; color: #666666; font: 400 26px Roboto; cursor: text; transit ...

No display of Vimeo channel and videos

Currently, I am utilizing the Vimeo API in conjunction with axios and react to access a specific channel. Although my code appears to be properly configured, upon compilation, I encounter the following error: TypeError: Cannot read property 'map&a ...

Issue encountered when attempting to push jQuery AJAX requests into an array

I'm attempting to store ajax requests in an array called deferreds. However, I'm consistently encountering the error message below: Uncaught SyntaxError: missing ) after argument list As a reference, I've been using this guide: Pass in an ...

What is the best way to serve individual static files in Express without revealing the entire "/static" directory?

For my new project, I am working on a simple setup that involves using JWT for authorization. The project is being served entirely through express, with no separation between frontend and backend. My goal is to dynamically serve specific HTML files based o ...

Issue with rendering Angular templates

Having just embarked on my AngularJS journey, I'm currently facing an issue with this specific code snippet. The following is an excerpt from my JavaScript file named cribsController.js: angular .module('ngCribs') .controller('cribsCo ...

What could be causing my array to update when the method is called live but not during unit tests?

One of my methods is called toggleSelect which adds and removes items from an array named selectedItems. This method functions perfectly when I test it live in the browser. However, when running unit tests, it does not seem to work as expected. Despite cal ...

Identifying the class name of SVGAnimatedString

While working on creating an SVG map, I encountered an issue where the functions triggered by hovering over 'g' elements were not functioning as expected. In order to troubleshoot this problem, I decided to check for any issues with the class nam ...

Unexpected object returned by the spread operator

Currently, I am utilizing node and specifically using babel-node. "start": "nodemon --exec babel-node --presets es2015 index.js" However, I have encountered an issue with my spread syntax in the following code snippet: export const login = async (parent ...

Setting up a secure Node.JS HTTPS server on Cloud9 IDE

Wondering if it's possible to set up a Node.js https server in the cloud9 IDE? Check out this example of a basic https server setup in Node.js. var https = require('https'); var fs = require('fs'); var app = require('./app& ...

Using curly brackets as function parameters

Can someone help me understand how to pass an emailID as a second parameter in curly braces as a function parameter and then access it in AccountMenuSidebar? I apologize for asking such a basic question, I am new to JavaScript and React. class Invoices ex ...

Changing URI to File Object using JavaScript

I have successfully retrieved the URI of a selected file in my Ionic app using the cordova-fileChooser plugin. Next, I used the cordova-plugin-filepath to obtain the absolute path of the file from the nativeURL on the phone. Now, the challenge is how do ...

Launching a modal in a new browser window with the help of JavaScript or PHP

I need to implement a feature where clicking a link opens a modal in a new tab and redirects the current page to a different link, similar to how retailmenot handles coupons. Here is the code snippet I am currently working with: <div onClick="myFunctio ...

Switching between API requests through a live feed

Hey there: import Rx from 'rxjs'; function mockApi(endpoint, time, response) { return new Rx.Observable(observer => { console.log(`${endpoint}: Request initiated.`) let active = true; const id = setTimeout(() => { cons ...

Navigating through arrays to access nested objects

Currently, I am attempting to retrieve a specific field within a nested array using the following code: var array1 = []; const data = { [userId]: [{ id: id, name: fullName, email: userEmail }, ], ...

The process of sending parameters to an API in ReactJS: a guide

My objective is to target .....the values originating from login (can be anything)-> for example email:'[email protected]' password:'12345678' I am required to extract the username until "@" and use it as a username i ...

What is the best way to create a feature in Vue that filters options in real-time as we type into a

In my Vue application, I am trying to implement dynamic filtering for the options in a search box as the user types. Currently, the search box displays the entire list of options without any filtering happening even when the user is typing. <el-form-it ...