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).

https://i.sstatic.net/UtthR.png

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

Singleton constructor running repeatedly in NextJS 13 middleware

I'm encountering an issue with a simple singleton called Paths: export default class Paths { private static _instance: Paths; private constructor() { console.log('paths constructor'); } public static get Instance() { consol ...

Tips for creating animations using parent and child components in Angular

Despite my best efforts, it seems like this should be functioning properly... but unfortunately it's not... I'm attempting to achieve a transition effect on the parent element (ui-switch-groove) while the child element (ui-switch-dongle) moves. ...

Can you explain why the .js code is causing such high CPU usage in popular video players?

Why is the .js code running continuously even when the video is paused and there is no user interaction? I observed this phenomenon on a Windows 10 Atom Tablet, particularly when in energy-saving mode. The CPU usage for video playback and decoding almost ...

Tips for invoking C language code from JavaScript by using the js-ctypes extension in Firefox

I need assistance with developing a Firefox extension that requires calling native C code. Here is my C program code: #include<windows.h> int add(int a, int b) { return(a + b); } And here is my JavaScript code: var {Cu} = require('chrome ...

Identify the user's default character encoding in order to provide the appropriate CSV file

Is there a way for the website to automatically serve CSV files encoded as windows-1252 to users on Windows workstations, and encoded as UTF-8 to other users? Currently, two URL links are used which requires the user to decide which one to click. Most use ...

In Angular and Typescript, adjusting the index in one dropdown will automatically update the selected option in another dropdown

I'm a newcomer to Angular and I could use some assistance with the following requirement: In my Angular template, I have two dropdowns. I want the selection in one dropdown to automatically reflect in the other dropdown. Both dropdowns pull their val ...

Tips for integrating AngularJS into a webpage

I am currently developing a NodeJS application and I am looking to integrate AngularJS for the client side scripting. After downloading AngularJS via NPM, I encountered an issue where my require statement is not functioning as expected. Can anyone provide ...

js extracting information from the XML response using response.text()

Currently, I am sending an ajax request to an API that returns data in XML format. Upon receiving the responseXml data, it gets displayed, but I'm unsure about how to parse it and access specific data elements such as item.line or item.origTime. Shou ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Minimize unnecessary rendering in React when toggling between tabs

I am currently working on a React application that utilizes material-ui to generate tabs. <div className={classes.root}> <AppBar position="static"> <Tabs value={value} onChange={handleChange}> <Tab label="Item One" /> ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

Combining an Angular factory with another factory

I'm facing some difficulties with injecting one factory into another. The error message I'm getting is: `ReferenceError: testDataService is not defined` I thought it would be a simple issue to resolve, but it's turning out to be quite c ...

An error in npm occurred: "The name "@types/handlebars" is invalid."

While attempting to install typedoc using npm, I encountered the following error: npm ERR! Invalid name: "@types/handlebars" To resolve this issue, I proceeded to install @types/handlebars directly by running: npm install @types/handlebars However, I r ...

How can we transfer parameters in JavaScript?

My vision may be a bit vague, but I'll try to explain it as best as I can. I want to implement multiple buttons that can toggle the visibility of a div (I have this functionality working already). Each button should carry two values (a number and a l ...

Retrieve the output of a JavaScript function and submit it as extra form data

I am working on a JavaScript function that looks like this: <script type="text/javascript"> function doSomething() { var s = 'some data' return s; } </script> and @using (Html.BeginForm(new { data_to_send = ...

CSS hover effect ceases to function after the button has been clicked once

I am facing a dilemma with styling that I can't seem to resolve. There is a basic toggle feature on my page with two options -- the user can select either Toggle1 or Toggle2, resulting in different data being displayed dynamically based on the active ...

Guide on efficiently injecting data into a database using JavaScript and SQL from an array of objects

Let's simplify this process. I am creating a dynamic form for clients to submit data to a PostgreSQL database using React on the front end and NodeJs on the back end. Once the form is filled out, the inputs are stored in an array of objects like this ...

The functionality of Vue JS v-attr="expression1 && exp2 && exp3" seems to be malfunctioning

Why aren't Vue JS v-attr=“expression1 && exp2 && exp3” working? I've attempted using ${&}${&}, #{&}#{&}, &amp;&amp;, and even #{&amp;}#{&amp;} The code can be found on JSFiddle <div id="dem ...

What is the best way to enable and disable the edit-in-place feature using jQuery?

Recently, I decided to experiment with the jQuery In Place Editor but I've come across an issue I can't seem to solve. Below is the code snippet that I have been working on. In my implementation, I am utilizing the jQuery toggle method to enable ...

Obtain JSON data using jQuery

Hey there! I am currently working on understanding how to retrieve data using json/JQuery with the code below. After storing a php variable in a json variable (var ar), I confirmed its contents through console.log, although when I used document.write it d ...