What are the most effective strategies for creating a function that sorts and filters arrays based on multiple parameters?

Within our game catalog, we have implemented a series of filters to streamline the process of finding games.

The games are grouped by platforms (HTC, PSVR, PS5, Favorites), and when you click on a specific tab, it triggers a calculated property called showPS5Games. This property takes into account various parameters such as selected genre, sorting preferences, checkboxes for "For children" and "For two," and the ability to search for games by name, tag, or genre. These parameters can be combined in any way to customize the gaming experience.

Here is the full code for showPS5Games:

showPS5Games: state => (
  query,
  genre,
  isChild,
  isLocalMultiplayer,
  selectedSort
) => {
 [Code snippet remains unchanged]

I initially developed a complex function with multiple conditional statements to cover all possible combinations, but this approach lacks optimization and visual appeal. Additionally, I've encountered an issue where filtering the array based on both selected checkboxes does not function correctly - only one checkbox works as intended. What would be the most effective way to refactor this code?

Answer №1

There appears to be a lot of repeated logic in this code snippet. A more efficient approach would involve tidying up the if statements, such as:

if (genre == "все" && isChild && isLocalMultiplayer) {
...
} else if (isChild && isLocalMultiplayer) {

Some of these conditions could potentially be combined within nested if statements:

if (isChild && isLocalMultiplayer) {
    if (genre == "все") {
    ...
    }
}

Furthermore, simplifying the returns for similar reasons would also be beneficial. For instance, the lengthy return statement below:

      return (
    (game.category == "ps5" &&
      isChild &&
      game.isLocalMultiplayer &&
      game.title.toLowerCase().includes(query)) ||
    (game.category == "ps5" &&
      isChild &&
      game.isLocalMultiplayer &&
      game.genre.includes(query)) ||
    (game.category == "ps5" &&
      isChild &&
      game.isLocalMultiplayer &&
      game.tag.includes(query))
  );

Could likely be condensed down to something like this:

 return (
    game.category == "ps5" &&
    isChild &&
    game.isLocalMultiplayer && 
   (game.title.toLowerCase().includes(query) || 
    game.genre.includes(query) ||
    game.tag.includes(query))
);

By making these adjustments, you may have a clearer path forward in resolving any other issues present in your code. Best of luck!

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

Can the key in a WeakMap be altered when setting an item within it?

When working with JavaScript, is it possible for setting an item in a WeakMap to change the object used as the key? I'm curious about this because if I were to create a WeakMap, my approach might involve using a Symbol on the key and then utilizing t ...

The issue with THREE.js ORBITCONTROLLS not responding to changes in mouse button settings is causing inconvenience

Hey there, currently working on a project using THREE.js and I've run into an issue with my .mouseButtons functionality. var controls = new THREE.OrbitControls( camera, renderer.domElement ); controls.target.set( 0, 25, 0 ); c ...

Vue-router: the browser tries to open a <router-link> element as if it were a local file

Having some trouble with Vue-router - when I click on a navigation link, the desired component briefly displays before the browser tries to open it as a file. For instance, clicking on the "Badger!" link results in the browser attempting to open a local f ...

How to access the api variable in JavaScript

When attempting to retrieve variables from an API object, I encountered the obstacle of them being nested inside another object named "0" in this particular case. Here is a screenshot from the console: enter image description here Below is the JavaScrip ...

Creating a JavaScript function that calculates the sum of values in a table

Here is a snippet of my HTML code: <TR Row="1" CLASS="ThemeAlignCenter"> <TD id="wrdActive_Row1" style="width: 50px" CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">6</SPAN></TD> .. ...

Disabling hammer.js touch events with the onclick event

I have recently completed constructing a carousel slider with touch events for a website project. I am currently trying to find a way to deactivate the touch events (hammer) using click events. Below is the code snippet that I have been working on: The cl ...

Program for Saving Facebook Photo Collection

Currently, I am delving into the world of JavaScript through a project aimed at creating a Facebook album downloader. My goal is to design a tool that can automatically download all images from a specific album on Facebook – for instance, this one: . Af ...

React functional components with checkboxes can trigger rerenders

I'm currently working with Gatsby and have a functional component that iterates through a set of data to generate a radio button group with an onchange event and a checked item. Whenever I update the state, the entire page component re-renders. I thou ...

tracking the number of new buttons pressed (HTML/Javascript)

As a novice in programming, I am currently tackling a task involving a table in otree that displays 256 unique buttons using Javascript. Each button reveals an icon when clicked, thanks to a straightforward function. Within this function, I have incorpora ...

What is the method for showcasing an array using AngularJs in my specific scenario?

I have an array in JavaScript structured like this: var data = [ 2005 = [ Jan = [0,1,2,3,5...], Feb = [0,1,2,3,5...], ...more ], 2006 = [ Jan = [0,1,2,3,5...], Feb = [0,1,2,3,5...], ...more ], 200 ...

Creating a customized TextField look with styled-components and Material-UI's withStyles feature

Take a look at this customized TextField style with Material-UI's withStyles: export const StyledTextField = withStyles({ root: { background: 'white', '& label.Mui-focused': { color: 'white' }, ...

Creating interactive web pages with Vue.js by adding HTML elements dynamically upon button click

My goal is to enable the user to add new information to an existing set that will be passed on to Vue from JSON. Below is my HTML code consisting of a div element with the id objectiveArea that Vue will render, and a button for users to add more entries: ...

Blazor Server: Seamless breadcrumb navigation updates with JavaScript on all pages

I have implemented a breadcrumb feature in my Blazor Server project within the AppLayout that functions for all pages: <ul id="breadcrumbs" class="breadcrumbs"> <li><a href="#">Home</a></li> ...

Determining a User's Connection Status in ReactJS: Cellular Network or WiFi?

Are there any tools or applications available that can determine if a user is connected to WiFi or using a cellular network? ...

Is it possible to access a class with protected/private fields written in TypeScript from outside the class in JavaScript?

Currently, I am delving into TypeScript classes (though my experience with OOP is limited). The following code snippet is extracted from the chapter on classes in https://www.typescriptlang.org/docs/handbook/classes.html Here's the issue at hand: I ...

Utilize the JavaScript .send function to pass an array

Can an array be passed to a PHP page using the code below? If not, what modifications are needed in the code? function ajax_post(){ var hr = new XMLHttpRequest(); hr.open("POST", "get_numbers.php", true); hr.setRequestHeader("Content-type", "a ...

Is it possible for me to know the loading time of a webpage?

Looking to add a pre-loading feature to my website: I'd like to have a loading indicator (spinner, loading bar, etc.) display prior to the actual page loading. An ideal scenario would be for the pre-loader to disappear once the main page has finishe ...

JavaScript ACTING UP -> CROSS-ORIGIN RESOURCE ACCESS ERROR

After extensive research and troubleshooting, it dawned on me that the issue was not with JavaScript itself. Instead, I was facing a cross origin resource exception, which occurred because the ajax request was unable to access my server script due to lac ...

Issues arise with the onscroll functionality when it is responsible for executing numerous conditional statements

My JavaScript function triggers various conditional statements based on the user's scrolling behavior. (Specifically, it adjusts the design of my navigation links as the window moves into different sections or rows.) // list of variables var pLink ...

Surprising behavior encountered while utilizing fsPromises.open with Node.js

As I work on a larger app, I encounter an issue with a file writing operation. I am utilizing fsPromises to generate an autosave file, but the path variable seems to lose its value between a console log for debugging and the actual call to open the file. I ...