Using JavaScript/TypeScript to sort through and separate two arrays

Creating a list of checkboxes on a UI allows users to toggle and filter data results. To achieve this, I am storing the selected checkboxes as a string array. The structure of my code is outlined below:

export interface IMyObjectFromAPI {
   status: {
      id: number,
      description: string,
      location: string,
      name: string,
      imageUrl: string
  }
}

var filteredByTerms: string[] = [];
var resultsFromAPI: IMyObjectFromAPI [] = [];
var filteredDataResults: IMyObjectFromAPI[] = [];

The API call results are saved in the resultsFromAPI array for further processing.

In the user interface, there are multiple checkboxes based on countries populated through an array loop. Upon selecting a checkbox, the following function is triggered. The objective here is to apply multiple filters (such as location + name) to the filter terms array:

filterDataResults(term: string) {
  var indexOfTerm = this.filteredByTerms.indexOf(term);
  
  if (indexOfTerm === -1) {
    this.filteredByTerms.push(term);
    this.filteredDataResults = this.resultsFromAPI.filter(x => x.location === 
                              this.filteredByTerms.includes(term));
  } else {
    this.filteredByTerms.splice(indexOfTerm, 1);
    this.filteredDataResults = this.resultsFromAPI.filter(x => x.location === 
                                this.filteredByTerms.includes(term));
  }
}

I hope I have clarified the process adequately; however, a visual aid has been provided to assist. The layout consists of checkboxes on the left, the dataset on the right, and the ability for checkboxes to accumulate selections (as shown in the linked image).

Answer №1

If you're looking to streamline your user-defined logic and filtering, considering using a combination of higher-order functions (HOFs) and mapping filters.

const filters = {
  lastHourFilter: (result) => result.postedDate > Date.now() - ms('1 hour'),
  last24HoursFilter: (result) => result.postedDate > Date.now() - ms('24 hours'),
  ...
  itContractorFilter: generateSpecialismFilter('IT Contractor'),
  clinicalPsychologyFilter: generateSpecialismFilter('Clinical Psychology'),
  ...
  fullTimeFilter: generateJobTypeFilter('Full Time'),
  temporaryFilter: generateJobTypeFilter('Temporary')
}

To apply these filters based on user selections, iterate over the checkboxes and apply the corresponding filters to the results:

function applyFilters(results) {
  Object.keys(filters).forEach((key) => {
    if (checkboxes[key].checked) 
      results = results.filter(filters[key]);
  });
  return results;
}

In this setup, 'checkboxes' is a map of checkboxes in the DOM that aligns with the keys used for the filters.

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

Exploring the Adjustment of State as well as Function in Next/React JS

I'm facing a challenge in my React project where I need to manage state and trigger a function across separate component files. Specifically, I have my main app file along with two components (header and sidebar) stored in the components folder. The h ...

Could we bypass the parent component somehow?

Just starting out with angular and decided to work on a small project. As I was setting up my routing, I encountered a problem. Here is the routing setup I have: const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: &a ...

Implementing custom color names in Material UI using TypeScript

Currently, I am utilizing Material UI alongside TypeScript and attempting to incorporate custom colors into my theme. While everything seems to be functioning properly, the VSCode linter is displaying the following message: Type '{ tan: string; lightR ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

How can the '!!user' syntax be utilized? What outcome does this code snippet produce?

I am looking to implement an angular route guard in my application. I came across this code snippet but I am confused about the line where user is mapped to !!user. Can someone explain the purpose of map(user => !!user) in this context? canActivate( ...

What is the best way to add a separator in a b-dropdown menu once the options have been loaded using Vue?

Here is the code snippet for my dropdown element: <b-dropdown id="SchemaDropdown" name="SchemaDropdown" variant="form-control" class="" style="width: 100%" ...

Using jQuery's .load function to load an HTML file from a href attribute into a div element may not function as

I'm struggling to populate the href section of my dropdown menu with my files. I'm attempting to dynamically load the files in the .where-you-tune class. Something must be off because I keep encountering (index):81 Uncaught TypeError: $(...). ...

Invoke a PHP function located in a separate file using a JavaScript function to fetch data from a database

How can I properly call a PHP function from a JavaScript function located in a different file? I am trying to pass a variable from an onClick function in JavaScript to a PHP function, which will then access a MySQL database to retrieve data. However, my c ...

Sticky sidebar panel featuring a stationary content block

I have a sidebar that is set to position:fixed; and overflow:auto;, causing the scrolling to occur within the fixed element. When the sidebar is activated, the element remains static on the page without any movement. My goal: I am looking to keep the .su ...

Tips for adjusting the font size of a Chip using Material-UI

I am using a widget called Chip const styles = { root:{ }, chip:{ margin: "2px", padding: "2px" } } const SmartTagChip = (props) =>{ const classes = useStyles(); return( <Chip style={{color:"white&q ...

Using JavaScript's Regex to match sentences, while ensuring any full stops within quotes are ignored

Here is the regular expression: (?:(?:Jr|Master|Mr|Ms|Mrs|Dr|Capt|Col|Sgt|Sr|Prof|Rep|Mt|Mount|St|Etc|Eg)\.\s+|["'“(\[]?)(?:\b(?:(?!(?:\S{1,})[.?!]+["']?\s+["']?[A-Z]).)*)(?:(?:(?:Jr|Master|Mr|M ...

What's the best way to use JavaScript to obtain the width of a 'css-pixel' based on a media query?

While there have been discussions on how to determine device sizes using media queries like Twitter Bootstrap, I am looking for a reliable way to achieve the same output using JavaScript. Specifically, I want to get the CSS media query pixel number rather ...

Steps for Verifying the Legitimacy of an AJAX Request

In the process of creating a website where users are required to solve puzzles quickly, I am utilizing JavaScript to track the time taken for each puzzle. However, I am concerned about the possibility of users manipulating this data before it is sent to th ...

Use the onclick event to submit a form, ensuring that it can only be submitted once

For a form, I am configuring the action and triggering submission using the onclick event of a div: <div class="action_button" onclick="document.forms['test'].action='url/to/action';document.forms['test'].submit()"> < ...

Wrapping a group of elements with opening and closing tags using jQuery

I have a collection of distinct elements, like so: <section class="box-1"></section> <section class="box-2"></section> <section class="box-3"></section> My objective is to enclose all three elements within a div with a ...

Having trouble getting MongoDB to connect correctly to my server (using node.js and express), any help would be greatly appreciated

Whenever I make an API request using Hoppscotch, I encounter a terminal error along with status code 500 on Hoppscotch. Despite my efforts to fix the issue, it persists. Below is the code snippet that I am currently working with: var mongodb = require(&apo ...

Nunjucks not loading the script when moving from one page to another

Currently, I am in the process of developing a website utilizing nunjucks and express. This website serves as a blog platform with content sourced from prismic. My goal is to load a script file for an active campaign form whenever a user navigates from a b ...

Is there a way for me to access the data stored in session storage in Next.js?

One of the components in my project is a slider, which allows users to set the number of columns in an Image Gallery component. This code snippet shows the implementation of the slider component: export default function Slider({ value, handleChange }: ISl ...

Failure of default option to appear in dropdown menu in Angular

I currently have a dropdown list in my HTML setup like this: <select id="universitySel" ng-model="universityValue" ng-options="university._id for university in universities"> <option value="-1">Choose university</option> ...

Avoiding drag events in hammer.js until the previous event is finished

I've been working on a basic photo gallery that switches images during a drag event. However, I'm encountering an issue with the iOS7 browser where the drag event gets triggered multiple times when dragging left or right. I attempted to use a glo ...