Implementing multiple condition-based filtering in React Native for arrays

I am looking to apply multiple filters to an array based on certain conditions defined by toggling switches. The issue arises when toggling two or more switches simultaneously, resulting in an empty array. My goal is to retrieve an array containing the true values of the toggled switches and eliminate all false values from the MEALS array.

https://i.stack.imgur.com/BBIbw.png

Here is a snapshot of the switch screen:

import React,{useState} from 'react';
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
import AnimatedLoader from "react-native-animated-loader";
import { ScrollView, Switch } from 'react-native-gesture-handler';

// Code for defining switches and logic

This is the filter logic:

// Filter logic to apply multiple conditions to the MEALS array

And this is the model structure:

// Model structure definition for Meal object

Finally, here is the MEALS array:

// MEALS array with sample data for meal objects

Answer №1

Unfortunately, recreating a react environment is not possible here. Instead, I have constructed the object route to filter the MEALS array (as provided by OP) based on the checked switches defined in route.params.filteredList:

// simulation of environment:
const route={params:{filteredList:{
 hasGroundMeat:1, hasCabbage:1}}};

class Meal {
 constructor(id,categoryIds,title,imageUrl,
  flag,duration,calories,servings,ingredients,steps,
  hasMeatCube,hasGroundMeat,hasTurkey,hasCabbage) {
   this.id = id;
   this.categoryIds = categoryIds;
   this.title = title;
   this.imageUrl = imageUrl;
   this.flag = flag;
   this.duration = duration;
   this.calories = calories;
   this.servings = servings;
   this.ingredients = ingredients;
   this.steps = steps;
   this.hasMeatCube = hasMeatCube;
   this.hasGroundMeat = hasGroundMeat;
   this.hasTurkey = hasTurkey;
   this.hasCabbage = hasCabbage;}
}
const MEALS=[new Meal('m1',['c1', 'c12'], 'كفتة', 
    [
        '../assets/Egyptian_Kofta.jpg',
        '../assets/Egyptian_Kofta2.jpg',
    ],
    'EG',
    45,
    1250,
    4,
    [
        '1 كيلو لحمة مفرومة',
        '1 بصلة مفرومة',
        '1 صفار بيضة',
      
    ],
    [
        'وضع اللحمة والملح والفلفل في بولة',
        'اضافة صفار البض والاوريجانو',
    
    ],
    false,true,false,true,false,false,false,false,false,
    false,false,false,false,false,false,false,false,false,
 
    ),
new Meal('m2',['c9', 'c13'], 'فراخ مشوية بالكرات', 
    [
        '..assets/Grilled_Chicken_Leeks_.jpg',
        '..assets/Grilled_Chicken_Leeks_1.jpg',
 
    ],
    'JP',
    25,
    4,
    750,
    [
        'نص كيلو افخاد دجاج مخلية بالجلد',
        'ملح وفلفل اسود',
        'صويا صوص',
 
    ],
    [
        'تقطيخ الفخاد لقطع صغيرة ',
        'نتبلها بالملح والفلفل',
        'نضيف الصويا على الفراخ',
  
    ],
    false,false,false,false,false,false,false,false,true,
    false,false,false,false,true,false,false,false,false,
 

),
new Meal('m3', ['c4', 'c13'], 'فراخ تندوري',
[
    '../assets/Tandoori_.jpg',
    '../assets/Tandoori_1.jpg',
],
'IN',
60,
4,
1200,
[
    'فرخة مقطعة منزوعة الجلد',
    'ربع كوب عصير ليمون',
    'فصين ثوم مفرومين',
],
[
    'نقطع الفرخة ارباع ونعمل فتحات بالسكينة علشان تتبل مكويس',
    'نحط التوابل والزبادي في الخلاط لغاية ما نعمل منهم معجون',
],

false,false,false,false,false,false,false,false,true,
false,false,false,false,false,false,false,false,false,
),

new Meal('m4',['c5', 'c14'], 'جمبري مشطشط بالكرفس والكاجو',
[
    '../assets/Spicy_Shrimp_Celery_.jpg',
    '../assets/Spicy_Shrimp_Celery_1.jpg',
],
'CN',
15,
4,
500,
[
    'كيلو جمبري مقشر',
    'بصل اخضر مقطع',
    'معلقة صويا صوص',
    'معلقة زيت سمسم',
    'معلقة هل ابيض',
],
[
    'نخلط الصويا صوص مع الخل وزيت السمسم',
    'نضيف الزنجبيل والثزوم والشطة',
    'نسخن طاسة تيفال لمدة دقيقتين',
],

false,false,false,false,false,false,false,false,false,
false,false,false,false,false,false,false,true,false,

),
];
// console.log(MEALS);

// The creation of the MEALS array appears unnecessarily complex and flawed as only the first four Boolean arguments are considered in each new Meal() call. The remaining 14 arguments are ignored.

Note that I have also modified the filtering method. In the MEALS.filter() callback function, you will find two approaches:

 // ingredients.some(ing=>fl[ing]&&meal[ing])
    ingredients.every(ing=>!fl[ing]||meal[ing])

The first alternative (commented out) necessitates at least one ingredient from filteredList to be present in a meal, while the second option requires all selected ingredients to be included.

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

Tips for creating a binding between an HTTP service and a variable in AngularJS that adjusts when the server data is modified

Using an http get request in angular to extract data into an object with the users currently connected to my app requires refreshing the information every time for binding to the scope. To achieve this, I implemented a method to refresh the data from the a ...

Iterate through an array of objects and add them to a fresh array

I am encountering an issue where I would like to generate a fresh array of objects in order to avoid utilizing a nested array map. However, the error message below is being displayed: TypeError: Cannot read property 'subscriber_data' of undefine ...

Querying Techniques: Adding an Element After Another

CSS <div id="x"> <div id="y"></div> <div> <p>Insert me after #y</p> The task at hand is to place the p tag after '#y', and whenever this insertion occurs again, simply update the existing p tag instead of ...

Increment the name field automatically and track the number of auto-increment variables being sent through serialization

I am trying to implement a functionality where users can add more inputs by pressing a button, each representing an additional 'guest'. The issue I am facing is with auto-incrementing the JavaScript so that new inputs are added with an incremente ...

Tips for increasing the height of a popover when clicked

When a user focuses on the password input, a popover displays information. At the bottom of the popover, there is a link. How can I make the popover expand when the user clicks on this link? I have tried adding an !important class for the height value, us ...

Tips on how to horizontally align an icon and text using Material UI

As a newcomer to Material UI, I am facing an issue where my icon and text are not aligned: What I'm aiming for: This is the code I have so far: <div style={{ display: 'inline-flex', VerticalAlign: 'text-bottom', Bo ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Why does this vow continue to linger unresolved?

I've been experimenting with a code that involves adding promises to a queue for processing in a non-blocking manner. One code snippet behaves as anticipated while the other doesn't, leaving me puzzled. Problematic Code: const axios = require(&a ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...

The form yields no response and fails to send any data

Ensuring that the form on this site successfully sends the name and phone number is crucial. However, upon clicking the send button, I encounter an empty modal window instead of a response indicating whether the data was sent or not. The contents of the fi ...

MaterialUI React components being stacked on top of each other

Currently working on a project with React and MaterialUI. Just about done with the setup, but I've run into an unexpected issue. The problem is that my simple navbar is overlapping the content beneath it. I set up a code sandbox to demonstrate the i ...

Repetitive data in a list with AngularJS

There's probably a simple solution to this: I have some data in a controller, and depending on whether an item is selected or not, it should display different HTML. If the item is selected, the HTML should be: <li> <a href="#"><s ...

Is there a way to prevent pop-up windows from appearing when I click the arrow?

Is there a way to display a pop-up window when the green arrow is clicked and then hide it when the arrow is clicked again? I tried using the code below but the pop-up window disappears suddenly. How can I fix this issue using JavaScript only, without jQue ...

Is it possible to utilize target="blank" in an external link when working with MDX?

For my latest project, I am developing a blog using NextJS and MDX. One of the features I would like to implement is opening external links in a new tab by adding a target="_blank" attribute. In typical Markdown syntax, I usually achieve this by using [wo ...

Using the onMessage event in React Native WebView does not seem to have any functionality

I'm having trouble with the onMessage listener in React Native's WebView. The website is sending a postMessage (window.postMessage("Post message from web");) but for some reason, the onMessage listener is not working properly. I can't figure ...

Tips for determining the datatype of a callback parameter based on the specified event name

Let's say we have the following code snippet: type eventType = "ready" | "buzz"; type eventTypeReadyInput = {appIsReady: string}; interface mysdk { on:(event: eventType, cb: (input: eventTypeCallbackInput) => void) => void } mysdk.on("ready", ...

The function react_toastify__WEBPACK_IMPORTED_MODULE_1__.toast.configure is not defined in this context

I have been attempting to integrate React Toastify for displaying notifications in our app, but I'm encountering an issue with the error message "react_toastify__WEBPACK_IMPORTED_MODULE_1__.toast.configure is not a function". The version of React-Toa ...

Effortlessly retrieving the id attribute from an HTML tag using jQuery

Currently, I am encountering an issue with a code snippet that is designed to extract the value from an HTML tag. While it successfully retrieves a single word like 'desk', it fails when attempting to do so for an ID consisting of two or more wor ...

Running NPM module via Cordova

After developing an app using cordova, I encountered a challenge where I needed to incorporate a node module that lacked a client-side equivalent due to file write stream requirements. My solution involved utilizing Cordova hooks by implementing an app_run ...

How to present MongoDB data on the frontend using Node.js without relying on a framework

As someone with experience in HTML, CSS, and JavaScript, I am new to Node.js and server-side programming. Although I can serve HTML pages using FileSystem and the request.url stream in NodeJS, I need assistance as I navigate through my first server-side la ...