Omit the items listed in the variable from the filtering process

When working with JSON data, I often use the .filter method to remove certain categories and products from my dataset. Individually specifying each filter condition can quickly become lengthy and cumbersome.

For example, instead of writing out each exclusion criteria like this:

var myfilter = myjson.filter(function(c) {
    return (c.category != 3 && c.category!= 5 && c.category!= 8 && c.category!= 11 && c.product != 191 && c.product != 139 && c.product != "string instead of int");
  });

I would prefer a more concise approach using arrays for excluded categories and products:

var excludedcats = [3, 5, 8, 11]
var excludedproducts = [191, 139, "string instead of int"]

var myfilter = myjson.filter(function(c) {
    return (excludedcats.includes(c.category) || excludedproducts.includes(c.product));
  });

While I'm not an expert in JavaScript, I believe this could simplify the filtering process by using arrays and a single 'return' statement.

My research on this topic hasn't yielded the results I hoped for, but I did come across some interesting insights on array handling in JavaScript here.

Answer №2

Here is a slightly modified version with more flexibility.

let myData = [{
    type: "A",
    value: 10
  },
  {
    type: "B",
    value: "string"
  },
  {
    type: "C",
    value: 0
  }
];

let restrictions = {
  type: ["X", "Y"],
  value: [123, "string"]
}


let filteredData = myData.filter(function(d) {
  for (let key in restrictions) {
    for (let i = 0; i < restrictions[key].length; i++) {
      if (d[key] == restrictions[key][i]) {
        return false;
      }
    }
  }
  return true;

});

console.log(filteredData)

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

Import txt file into numpy array

I am trying to import a text file into a numpy array with the following format: 1,10,1,11,1,13,1,12,1,1,9 2,11,2,13,2,10,2,12,2,1,9 3,12,3,11,3,13,3,10,3,1,9 4,10,4,11,4,1,4,13,4,12,9 4,1,4,13,4,12,4,11,4,10,9 1,2,1,4,1,5,1,3,1,6,8 1,9,1,12,1,10,1,11,1,13 ...

Adjust the formatDate function in the Material UI datepicker

I recently implemented the material-ui datepicker component with redux form and it's been working great. However, I have encountered a minor issue. Whenever I change the date, it displays in the input field as yyyy-mm-dd format. I would like it to app ...

Moving Angularjs table rows to another tableMoving table row from one Angular

I need a solution for transferring rows from one table to another. Here are the two tables involved: First Table: <table> <tr ng-repeat="row in items"> <td>{{row.PRODUCTDESCRIPTION}}</td> <td><inpu ...

Utilizing window.matchMedia in Javascript to retain user selections during page transitions

I am encountering difficulties with the prefers-color-scheme feature and the logic I am attempting to implement. Specifically, I have a toggle on my website that allows users to override their preferred color scheme (black or light mode). However, I am fac ...

Distinguish between RegisterClientScriptBlock and RegisterStartupScript with the response.write("script") method

Could you please provide an explanation and the unique advantages of using RegisterClientScriptBlock, RegisterStartupScript, and response.write("script"); individually? I have gathered some information such as: The RegisterClientScriptBlock() method inje ...

What is the process for fetching and storing a binary file video in Flask's Blob?

I've been dealing with a video encoding issue for the past few days and I need some help. Objective: Capture a video from my laptop's webcam using a VueJS frontend application. Send this video to a Python Flask app on the backend via FormData u ...

Adding npm packages to your Vue.js application

My Vue app is structured like this (auto created by vue init webpack myProject): index.html components/ -main.js -App.vue I am trying to include npm packages, such as https://github.com/ACollectionOfAtoms/atomic-bohr-model. Following the instructions, I ...

What could be the reason behind PHP not picking up my AJAX request string?

I'm encountering an issue where PHP is not recognizing my request string as defined. When I include $_GET['ask'] in my PHP file, it triggers the error message - Notice: Undefined index: ask. Interestingly, when I manually input the query in ...

Display the invoice bill using text in a Vue component

Hello, I am looking to print an invoice that resembles the one shown in this picture https://i.sstatic.net/6mzwe.jpg However, when I try to print it, I get a different output with some additional elements https://i.sstatic.net/uaKZC.jpg I am using vue. ...

Utilizing Highcharts to visualize data from a mysql database through a dynamic Pie Chart

I am currently working on generating a pie chart using highcharts to visualize the distribution of each value assigned to a specific column (TYP_CODE) relative to the total number of entries. synthese.php : <?php session_start(); if(!isset($_S ...

Leveraging jQuery and JSON to retrieve the current user's information

Currently facing a challenge in my project. As someone who is new to jQuery and JSON, I'm trying to retrieve the username of the logged-in user. While I can successfully extract all the information from the user table, I specifically need the user nam ...

Tips for activating a button and navigating to the following index in an array

I'm new to Android programming and I'm facing a challenge. I am populating an ArrayList by retrieving objects from a database. public ArrayList<Box> findBoxPerLine() { boxes = new ArrayList<Box>(); Cursor cursor; ...

Transforming JSON data into arrays that can be easily observed

How can I process the following JSON data effectively? [{ "title":"Things", "text":"1. Raindrops on roses 2. Whiskers on kittens 3. Bright copper kettles 4. Warm woolen mittens 5. Brown paper packages" },{ "title":"Colors", "text":"1. White 2. Blu ...

Retrieving data from an Array

I've encountered a peculiar issue while working on a test project. It seems that I am unable to access values in an array. pokemonStats$: Observable<PokemonStats[]>; getPokemonStats(id: number): any { this.pokemonStats$ .pipe(take(1)) .subscrib ...

Change not accepted

I am a beginner in Angular and still grappling with the fundamentals. On my menu, I have a cart icon with an initial value of 0 upon first load. In my product list, each product has an 'AddToCart' button. What I aim to achieve is- I want to dy ...

It never fails to function automatically, no matter which script is being executed

By default, the script will always be executed regardless of its environment. Check out my code snippet: import { Pool } from 'pg'; import config from './../config'; const connectionString = () => { switch (process.env.NODE_EN ...

Using Node.js and Express to assign a JavaScript property to a variable

Feeling a bit lost here, struggling with the "too noob to know what to search for" syndrome. In my Node/Express app, I'm attempting to retrieve user information from a mySQL DB and pass the user's email to an Infusionsoft API. When I hardcode th ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

Employing buttons and state to eliminate an item from a roster

My list is generated using the following code: return (this.state.limit).fill().map((_,index) => { return ( <div key={`${index}`}> Item </div> ) ) I'm wondering how I can implement a button that allows me to remove a specific ...

Having trouble logging JSON data from nodejs + express while serving static files through express. However, I am able to see the data when I only make a GET request for the JSON data without the static files

Currently, I am experimenting with sending data from a nodejs + express server to the front-end static files. The objective is for JavaScript (allScripts.js) on the front-end to process this data. At this stage, my aim is to log the data to the console to ...