Steps for embedding a "string includes" functionality within an Angular filter

Currently, I am in the process of implementing a filtering system using checkboxes. Within my geojson data, there is a property called "status" which can have values like:

status : "Act 3Q99"

or

status : "Fut 3Q99"

My objective is to filter based on either "Act" or "Fut". Below is the code snippet for my filter:

   function StatusFilter() {

    return function (territorySubdivisions, typeFilter) {
        var filtered = [];
        angular.forEach(territorySubdivisions, function (subdivision) {
            if (typeFilter.active == true && typeFilter.future == true) {
                filtered.push(subdivision);
            }
            else if (typeFilter.active == true && typeFilter.future == false && subdivision.properties.status == subdivision.properties.status.indexOf('Act') != -1) {
                filtered.push(subdivision);
            }
            else if (typeFilter.future == true && typeFilter.active == false && subdivision.properties.status == subdivision.properties.status.indexOf('Fut') != -1) {
                filtered.push(subdivision);
            }
        });
        return filtered;
    };
};

This is the approach I have attempted:

subdivision.properties.status.indexOf('Act') != -1

Unfortunately, the above code is not yielding the desired results. In order to isolate any potential conflicts, I have included additional code for sorting and filtering in a working Plunker example.

View the working Plunker here

   <div class="col-xs-3">
            <div class="checkbox checkbox-success checkbox-inline">
                <input type="checkbox" id="active-checkbox-filter" ng-model="vm.typeFilter.active" ng-change="vm.statusActive('active')">
                <label for="active-checkbox-filter"> Active </label>
            </div>
        </div>
        <div class="col-xs-3">
            <div class="checkbox checkbox-success checkbox-inline">
                <input type="checkbox" id="future-checkbox-filter" ng-model="vm.typeFilter.future" ng-change="vm.statusFuture('future')">
                <label for="future-checkbox-filter"> Future </label>
            </div>
        </div>

Answer №1

Here is a revised version of @Mate's response, focusing on applying the "Don't Repeat Yourself" principle:

let active = typeFilter.active;
let future = typeFilter.future;
let status = subdivision.properties.status;

let match = (active && future) ||
            (active && !future && status.includes('Act')) ||
            (future && !active && status.includes('Fut'));

if (match) {
    filter.push(subdivision);
}

It is worth noting that once you have the boolean match value, you can leverage Array.filter to generate the desired outcome instead of gathering the results using .push. This method is supported on MSIE 9+ and thus will function on any browser compatible with AngularJS, simplifying your code as shown below:

function StatusFilter() {
    return function (territorySubdivisions, typeFilter) {
        return territorySubdivisions.filter(function(subdivision) {
            let active = typeFilter.active;
            let future = typeFilter.future;
            let status = subdivision.properties.status;

           return (active && future) ||
                  (active && !future && status.includes('Act')) ||
                  (future && !active && status.includes('Fut'));          
        });
    } 
}

Answer №2

Your code appears to be in need of some improvement. Perhaps consider the following revision:

if (typeFilter.active && typeFilter.future) {
    filtered.push(subdivision);
} else if (typeFilter.active && !typeFilter.future && subdivision.properties.status.indexOf('Act') >= 0) {
    filtered.push(subdivision);
} else if (typeFilter.future && !typeFilter.active && subdivision.properties.status.indexOf('Fut') >= 0) {
    filtered.push(subdivision);
}

Is this what you were looking for?

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

When utilizing Expo, importing a module may result in returning null

I've been attempting to incorporate a compass module into my project using expo and react native, but I'm encountering some issues. Check out the library here The problem arises when I try to import the module. Here's the error message I r ...

There seems to be a limitation in JS/JQuery where it is unable to append HTML that spans

I am encountering an issue with retrieving data in a div element. It seems that the function provided does not work correctly for files larger than a single line of code or even possibly a string. What can be done to resolve this? <ul class="dropdo ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

Filtering substrings in an Angular data resource

DEFAULT_RECORDS = [{ id: 1, name: 'John Evans', number: '01928 356115' },{ id: 16, name: 'Murbinator', number: '053180 080000' }]; - retrieveEntries: function (name) { var foundRecords = {}; ...

An error was encountered when attempting to use the 'await' syntax in a useEffect() function that called axios.get()

To avoid using .then(..), I have switched to utilizing await. I am making a call to a function that includes an Axios request and returns the data as response.data after awaiting for it. My functional component has a useEffect that is meant to initialize a ...

Animations experiencing delays on mobile Chrome

I am currently exploring the world of website animations. I have a version of the jsfiddle code linked below that is similar to what I am working on. The animations function perfectly when viewed on desktop, but when accessed on mobile - specifically on my ...

Verifying if form submission was done through AJAX using PHP

Hey there, I need some help with checking whether or not this ajax method has been submitted. I want to display the result based on a certain condition. Below is the code for the Ajax POST request: $.ajax({ url: "addorderInfo.php", // This ...

Moving pictures using css3 transitions

Trying to create a straightforward image slider. Below is the provided JavaScript code: $(document).ready(function() { $('#slide1_images').on('click', 'img', function(){ $("#slide1_images").css("transform","translateX ...

When you log a JavaScript array after making a call using $.ajax, it may return an index

I am experiencing an issue with my array of 10 elements. When I log their key, value pairs in a loop, they are correctly ordered. $.each( sArray, function(i, k) { log(i, k); // log(i, k) returns correctly // [0] ELEMENT ONE // [1] ELEMENT TW ...

The elusive three.module.js file has gone missing, leaving behind a trail of 404 errors

It seems like a simple mistake, but I'm encountering a 404 error for a file that actually exists: http://localhost:8000/Desktop/Skeletor/js/build/three.module.js net::ERR_ABORTED 404 (File not found) The correct path should be http://localhost: ...

Babel fails to substitute arrow functions

After setting up babel cli and configuring a .babelrc file with presets to es2015, I also installed the es2015 preset. However, when running the command babel script.js --out-file script-compiled.js, I noticed that arrow function syntax (=>) was still p ...

Handsontable's unique text editor feature is encountering a tricky issue with copying and pasting

In my table, there are two columns: name and code. I have developed a simple custom editor for the code column, where the user can double click on a cell to open a custom dialog with a code editor. You can view a simplified example of this functionality he ...

Please provide both an image and text in addition to a progress bar by using the form to

I am working on a form that needs to store both images and text data in a database. <form action="processupload.php" method="post" enctype="multipart/form-data" id="UploadForm"> <input name="name" type="text" /> <input name="age" ty ...

Display a concealed div when an ng-click event occurs within an ng-repeat loop

$scope.editPostComment = false; Whenever I click on the button, it displays the textarea in all the repeated items instead of just the clicked div! <div class="commentBox" ng-show = "editPostComment"> <textarea name="editor2" ...

Establish a timeout period for ajax requests using jQuery

$.ajax({ url: "test.html", error: function(){ //do something }, success: function(){ //do something } }); At times, the success function performs well, but sometimes it does not. How can I add a timeout to this ajax re ...

Angular encountered an issue while attempting to load base64 images

I have encountered an issue in my Angular application while trying to load images downloaded from the server as base64. Although I am able to see the images in the app without any difficulty, there are some errors being displayed in the console: https://i ...

The logout confirmation message functionality in Laravel 8 is malfunctioning

In my Laravel project, I am attempting to implement a logout confirmation message that will pop up when a user clicks on the logout button. Here is the code I have added to my navbar.blade.php: <a class="dropdown-item" id="logout" hr ...

You are unable to define a module within an NgModule since it is not included in the current Angular compilation

Something strange is happening here as I am encountering an error message stating 'Cannot declare 'FormsModule' in an NgModule as it's not a part of the current compilation' when trying to import 'FormsModule' and 'R ...

What is the Ideal Location for Storing the JSON file within an Angular Project?

I am trying to access the JSON file I have created, but encountering an issue with the source code that is reading the JSON file located in the node_modules directory. Despite placing the JSON file in a shared directory (at the same level as src), I keep r ...

Is it recommended to aggregate data from various tables in a REST API to create a JSON response?

I am interested in exploring various REST API standard patterns. My current implementation follows a NoSQL style, where one table contains objects (Agenda Items) each referencing records in another table (Documents). In the UI I am developing, users can se ...