Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string:

const filteredString =  `${this.filter}`.toLowerCase();
     this.filteredCampaigns = this.filteredCampaigns.concat(this.allCampaigns.
            filter((item) => item.description?.toLowerCase().includes(filteredString) ||
            item.type?.toLowerCase().includes(filteredString) ||
            item.code?.toLowerCase().includes(filteredString)
            ));

If you need to match multiple strings, split the input string into an array like this:

const filteredString: string = `${this.filter}`.toLowerCase().split(' ');

To filter based on all elements of the array together instead of individually, use a for-of loop:

for (const val of filteredString) {
            this.filteredCampaigns = this.filteredCampaigns?.concat(this.allCampaigns.
              filter((item) => item.description?.toLowerCase().includes(val) ||
                item.type?.toLowerCase().includes(val) ||
                item.code?.toLowerCase().includes(val)
              ));
          }
        }

The issue here is that each element in the array is filtered independently. If you want all items in the array to be connected in filtering, and return results that match all elements, you'll need a different approach.

Answer №1

Input your filter criteria here.

const filter = 'not that';

List of filters separated by spaces.

const filteredStrings: string[] = `${filter}`.toLowerCase().split(' ');

If you have campaign data available.

const allCampaigns = [{
    description: 'This is ...',
    type: 'TYPE1',
    code: 'TD35'
  },
  {
    description: 'That will be done...',
    type: 'TYPE2',
    code: 'TC33'
  },
  {
    description: 'You shall not pass',
    type: 'UUGG',
    code: 'CD01'
  }
];

Campaigns after filtering

let filteredCampaigns: any[] = [];

Filtering method:

filteredCampaigns = filteredCampaigns?.concat(allCampaigns.filter((item) => filteredStrings.filter(val => item.description?.toLowerCase().includes(val)).length ||
  filteredStrings.filter(val => item.type?.toLowerCase().includes(val)).length ||
  filteredStrings.filter(val => item.code?.toLowerCase().includes(val)).length
));

View Demo

Answer №2

To implement this logic, you can destructure the 'item' variable and then verify if any of the words in the filter match one of the values.

const
    filter = this.filter.toLowerCase().split(/\s+/);
    
this.filteredCampaigns = this.allCampaigns.filter(({ description = '', type = '', code = '' }) =>
    [description.toLowerCase(), type.toLowerCase(), code.toLowerCase()]
        .some(word => filter.includes(word))
);

Answer №3

Instead of simply adding the matches to an array, I opt to create individual arrays for each string's matches initially. Then, I compare the total number of matches with the count of filtered strings.

If all strings yield matches, I convert the filteredCampaigns array from a two-dimensional structure to one-dimensional.

Otherwise, I clear out the filteredCampaigns and set it back to an empty array.

const filteredString: string = `${this.filter}`.toLowerCase().split(' ');
this.filteredCampaigns = [];

for (const val of filteredStrings) {
  this.filteredCampaigns.push(this.allCampaigns.filter(item => item.description?.toLowerCase().includes(val) || item.type?.toLowerCase().includes(val) || item.code?.toLowerCase().includes(val)))
}

if (this.filteredCampaigns.length == filteredStrings.length) this.filteredCampaigns.flat();
else this.filteredCampaigns = [];

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

How come lazy loading isn't functioning in my React project?

Check out my project: link. This project includes routers and lazy-loaded components for each page. Here's a brief example of a router component: export const RoutersComponent = () => { return ( <HashRouter basename={'/'}> ...

Turn off the ability to drag on an HTML page

Need help with creating an HTML etch-a-sketch! I have a div container with multiple div elements inside it, all set up with CSS grid display. HTML structure: <div id="canvas"></div> To populate the canvas with div elements, I'v ...

Standardize date formatting in AngularJS

Retrieve the date in the shared format: {{ dateValue | date:{{dateFormat}} }} The following service is provided: app.service('formatting', function() { var format = new Object(); format.dateFormat = 'medium' var ...

Utilizing React JS to Develop Cell Components for a Schedule, Ensuring Teams are Unique within the Same Row

I am currently facing a challenge involving a table that has a fixed number of timeslots (y axis) and pitches (x axis). In addition, I have a collection of match objects with the following structure: Object { id: 3, teamA: "pelt", teamB: "Ranelagh" } Eac ...

Iterate through the collection to retrieve the value associated with a specific key

In the JSON response I have received, I am trying to extract the value of "fees" corresponding to "detailComponent" with the identifier "FULL_FEE". However, instead of retrieving the desired value, the loop seems to be fetching the last value associated wi ...

Transferring information from a function-based module to a higher-level class component in React Native

I'm currently working on an application that has a tab navigation. One of the screens in the tab is called "ScanScreen," where I'm trying to scan a UPC number and send it to the "HomeScreen" tab, where there's a search bar. The goal is for t ...

Facing difficulty in accessing mongoose schema static method in TypeScript

I am currently facing an issue where I have a method called "findByToken()" defined in the model and implemented as a static method in the userSchema. However, in another part of my application, I am unable to access the method using: User.findByToken(tok ...

Organizing the AuthGuard(canActivate) and AuthService code in Angular 2

After working on my current code, I have encountered an issue when routing to a page with the canActivate method. I was able to retrieve authentication data from the server using the following setup auth.guard.ts (version 1) import { CanActivate, Activat ...

Integration of elFinder with TinyMCE 4

Has anyone attempted to integrate elFinder into the latest version (4b1) of TinyMCE? The previous implementation seems to be not working. If you have any snippets or tips, please share. Thank you very much. ...

Table order is requested, but the index fails to comply

I am facing an issue with sorting and deleting data from a JSON table. Even after sorting the columns, clicking "Delete" removes the wrong entry because the $index is not updated properly. Here is the JavaScript code I am using: $scope.friends = ...

JavaScript - Imported function yields varied outcome from module

I have a utility function in my codebase that helps parse URL query parameters, and it is located within my `utils` package. Here is the code snippet for the function: export function urlQueryParamParser(params: URLSearchParams) { const output:any = {}; ...

Sending Angular base64 image data to the server

I am encountering an issue while attempting to upload a base64 image from Angular to ExpressJS. The image is being created using html2canvas to generate the base64 representation. When I try to upload the imageData in its current format, I receive an error ...

How can one smoothly rewind X frames in a video or animation on a webpage without experiencing lag?

For my thesis presentation, I decided to make it available online as a video with custom controls resembling a powerpoint slideshow. The challenge I encountered was with transitions between slides in an animated video. Certain transitions needed to loop fo ...

Creating a TypeScript function that can dynamically assign values to a range of cells within a column, such as AD1, AD2, AD3, and so on

Hello there I'm currently working on a function that will dynamically assign values to the column range of AE to "AD" + i. However, when I use the function provided below, it only writes AD5 into the first 5 columns instead of AD1, AD2, AD3, and so o ...

Combining TypeScript and JavaScript for efficient mixins

I came across an article on MDN discussing the usage and creation of mix-ins (link). Intrigued, I decided to try implementing it in TypeScript: type Constructor = new (...args: any) => any; function nameMixin(Base: Constructor) { return class extends ...

How can I most effectively establish defaultValues for react-hook-form in this scenario?

I am working on a static Next.js website with only frontend functionality. In the pages/feedback/[id]/edit.tsx page, I need to dynamically retrieve an id and set default values in a nested FeedbackForm component. export const FeedbackForm = ({ editing }: { ...

The jQuery.ajax request encounters issues within a Chrome extension

I'm in the process of migrating one of my Firefox browser extensions to Chrome, and I've encountered an issue related to an AJAX query. The code snippet provided functions correctly in the Firefox extension but fails with a status of "0" when exe ...

Developing a databound listview in Ionic: A step-by-step guide

In the world of programming, each platform has its own way of handling lists. For example, Android uses RecyclerView, WPF uses ListView, and in Ionic, we have ion-list. If you have a list of strings like this: Animals:string[] = ["Dog", "Cat", "Human", "C ...

AngularJS is not immediately responsive to changes in $window.document.visibilityState

I am currently working with AngularJs version 1.4 and I need to be able to detect when a user is not on the tab of my app and when they return. To achieve this, I attempted using $watch in the following way: $rootScope.$watch(angular.bind($window, functio ...

What is the best way to access a variable within the .each() function in jQuery?

One common dilemma often faced is figuring out how to ensure that markup remains accessible within the scope of this .each() function. Instead of focusing solely on resolving this specific issue, my interest lies more in discovering a method to access ext ...