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

Troubleshooting Port Issue When Deploying Node/Sequelize Application on Heroku

I am in the process of developing a Node/Postgres application that will be deployed to Heroku. During my attempts to launch the app in a production environment, I encountered a timeout error. According to Heroku, this error is likely due to database or por ...

Facing the issue of "Protractor not syncing with the page" while trying to navigate an Angular website

I'm currently attempting to follow the tutorial for Protractor on the official Protractor website, but I've hit a roadblock at step 0. My setup involves using protractor and webdriver-manager version 6.0.0. I am running Linux (Ubuntu 18.06) as m ...

Can grapesjs be integrated into AngularJS using a controller?

JavaScript Question var app = angular.module('CompanyProfile', []); app.controller('CompanyProfileCtrl', function() { function initializeEditor() { var editor = grapesjs.init({ allowScripts: 1, ...

What is the reasoning behind ethers.js choosing to have the return value of a function be an array that contains the value, rather than just the value itself

An issue arose with the test case below: it('should access MAX_COUNT', async () => { const maxCount = await myContract.functions.MAX_COUNT(); expect(maxCount).to.equal(64); }); The test failed with this error message: ...

Having a Jquery resizing problem? No worries! When the width is less than 768, simply enable the click option. And when the width is

HTML <div class="profile"> <a href="#" class="hoverdropdown" onclick="return false;">Profile</a> <ul class="dropdown" style="display: none;"> <li><a href="#">Dashboard&l ...

The hover feature on my website is making the picture flicker

I am experiencing an issue with a map on my website that contains four colored squares. When I hover over one of the squares, the image of the map changes to show the route corresponding to that color. However, this causes the image to shift position and i ...

TS2304 TypeScript (TS) Unable to locate the specified name

Encountering an error message stating Cannot find name 'Record'. Do I need to install a specific package for this class? Severity Code Description File Project Line Suppression State Error TS2304 (TS) Cannot find name 'Record ...

Require modification of JSON values in React Promise code

Looking to modify the data returned from a promise and wrap a link around one of the fields. Here is the React code: this.state = { medications: [], } queryMeds().then((response) => { this.setState({medications: response}); }); The response c ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...

Div element to animate and vanish in a flash

I'm attempting to create a smooth slide effect for a div element before it disappears. Below is the code I am currently using: function slideLeft(element) { $("#" + element).animate({ left: "510" }, { duration: 750 }); document.getEle ...

Unleashing the Power of Dynamic JSON Data Access

I am facing an issue with my React Child component. Here is the code snippet: const SingleProject =(props)=>{ let data = projectData.VARIABLE_FROM_PROPS.projectDetails; let asideData = projectData.VARIABLE_FROM_PROPS.projectSideBar; useEffe ...

Property '{}' is not defined in type - Angular version 9.1.1

Currently, I am working with Angular CLI version 9.1.1 and I am attempting to update certain data without updating all of it. form: UserInfo = {adresse : {}}; UserInfo.interface export interface UserInfo { id_user: string; username: string; em ...

What is the best way to exclude a particular character from a text element utilizing jquery?

Looking to extract the numerical value from a div containing: <div class="balance"...>$500.48</div> The goal is to retrieve 500.48 as a number, not a string. One approach is to use alert($(".balance").text()) to verify that the content is ret ...

Enhance the functionality of your Rails application by implementing Ajax or jQuery to asynchronously load table elements separately from the page

Currently, I am facing an issue with a page that displays a list of user sites. The problem lies in the fact that I am making an API call for each site to check its status, which is causing the page to load very slowly. To address this issue, I would like ...

Is there a way to retrieve keys of the object from this combination type?

Can someone please help me understand how to retrieve keys from this union type? The Value is currently being assigned as a never type. I would like the Value to be either sno, key, or id type Key = { sno: number } | { key: number } | { id: number }; typ ...

Properly defining a DI service in Angular 2.1.2 using ES5

I have created an Angular 2 service that utilizes the Http service and is accessed by other components. However, I am unsure if my implementation is correct: (function (app) { 'use strict'; app.LoaderService = ng.core.Component({ providers: ...

What are the steps for loading JSON data into a select dropdown with the help of AJAX?

I am trying to create a dropdown list of schools using the select tag. Currently, I have hard coded values for the list, but I want to fetch the data from a RESTful service instead. Can someone please provide guidance on how to achieve this? <html& ...

Is there a feature in Angular similar to Vue.js's "computed property" functionality?

After mastering Vue.js, I recently dove into Angular 4 for a new project. I've found that most things in Angular are quite similar to Vue, with the notable exception of "Computed Property". In Vue, I could easily create a computed property that would ...

Creating keys for my console.log data and appending it to html in order to display console log results in textboxes

I am currently developing a matching system for Player vs. Player battles and I need to ensure that the keys are appended correctly to my div element. Previously, I have successfully used append with keys before. Below is the code snippet: ...

Angular Nested Interface is a concept that involves defining an

Looking for guidance on creating a nested interface for JSON data like this: Any help is appreciated. JSON Structure "toto": { "toto1": [], "toto2": [], "toto3": [], } Interface Definition export interface Itot ...