Create dynamically generated expressions to filter a JavaScript array

Looking to refine an array based on a variable number of items in another array. Consider the initial array:

var toBeFiltered = [
  {name:"A", parentId: 0},
  {name: "B", parentId: 3},
  {name: "C", parentId: 0},
  {name: "D", parentId: 1},
  ...
]

I want to filter out all elements for which parentId matches any value from another array (let's call it filtering = [3,1,0], although the length can vary). How would one create a dynamic filtering expression based on the contents of the filtering array? In this scenario, the resulting expression could look like:

function(d){return d.parentId == 3 || d.parentId == 1 || d.parentId == 0;}

Is there an efficient method to achieve this? Perhaps combining boolean expressions somehow?

Answer №1

To check if an item exists in an array, you can utilize the indexOf method.

The indexOf method will return the first occurrence of the specified value in the array, and it will return -1 if the value is not found.

var toBeFiltered = [
  {name:"A", parentId: 0},
  {name: "B", parentId: 3},
  {name: "C", parentId: 0},
  {name: "D", parentId: 1},
  {name: "E", parentId: 4}
]
var filtering = [3,1,0];
toBeFiltered=toBeFiltered.filter(a=>filtering.indexOf(a.parentId)!==-1);
console.log(toBeFiltered);

You can also make use of the Set feature introduced in ES6.

var toBeFiltered = [
  {name:"A", parentId: 0},
  {name: "B", parentId: 3},
  {name: "C", parentId: 0},
  {name: "D", parentId: 1},
  {name: "E", parentId: 4}
]
var filtering = new Set([3,1,0]);
toBeFiltered=toBeFiltered.filter(a=>filtering.has(a.parentId));
console.log(toBeFiltered);

Answer №2

One approach is to utilize Array#includes

var toBeFiltered = [{ name:"A", parentId: 0 }, { name: "B", parentId: 3 }, { name: "C", parentId: 0 }, { name: "D", parentId: 1 }],
    filtering = [1, 0], // to avoid obtaining the same array as the original
    result = toBeFiltered.filter(o => filtering.includes(o.parentId));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

How can I transform a collection of objects into an array using Javascript?

What would be the best way to convert this content into an array? https://i.sstatic.net/H6Fo9.png I have this: ...

Utilizing PHP to iterate through an array of MySQL data

Currently, I am developing a roster/calendar system and facing difficulties due to my limited knowledge of PHP arrays. The specific issue at hand involves two date cells labeled 17/08/2017 and 18/08/2017. On these dates, 2 staff members are scheduled on t ...

Creating a submit button in PHP and JavaScript

I am facing an issue with developing a submit button using JavaScript. On my webpage, I have both a registration and a login form placed together. The problem arises when I click on the login button - instead of accessing the login details, it redirects to ...

Tips for choosing and controlling Google Maps markers using their unique identifiers (V3 JS API)

Currently, I have a Google Map that displays markers on the left side and a list with explanatory content items corresponding to each marker on the right side. When a marker is clicked, the list will automatically scroll to the relevant entry. This functio ...

Establishing a system for utilizing barcode multimarkers in AR.js

Currently, I am attempting to configure AR.js for multimarkers, as illustrated in this image: barcode markers on wall. The plan is to display a single video within the area encompassed by the markers. Despite my efforts to set up the multimarker player an ...

In order to activate the input switch in Next.Js, it is necessary to initiate a

Currently, I am working on implementing an on-off switch in Next.Js. To seek assistance, I referred to this helpful video tutorial: https://www.youtube.com/watch?v=1W3mAtAT7os&t=740s However, a recurring issue I face is that whenever the page reloads, ...

Issue with Firefox not recognizing keydown events for the backspace key

I am currently developing a terminal emulator and have encountered an issue with capturing the backspace key in Firefox. While I am able to capture the first backspace press and delete the last character in the input prompt, the problem arises when trying ...

Store the numeric value in JavaScript as a PHP integer

My goal is to obtain the width of the browser and then compare it as a PHP variable. However, the issue I am facing is that it is being saved as a string, and my attempts at parsing it to another variable only result in returning 0. $tam='<script& ...

How to Parse a JSON Array with Newtonsoft.Json

Recently, I encountered an array of JSON objects that looks like this: [{"GroupID":5},{"GroupID":47}] I'm wondering about the correct method to deserialize it. In my code, I have a Group object defined as follows: public class Group { ...

Group by month and calculate the total sum using mongoose in MongoDB

I'm currently working with the orderdetails model in my project. Here is a snippet of the schema: const model = new Schema( { district: { type: String }, category: String, producer: String, variety: String, qty: String, price ...

Loading a Float32Array into Node v8 using C++

After thoroughly reviewing the documentation: Float32Array ArrayBuffer Array I am attempting to fill a v8 array with floats by utilizing a thrust::host_vectofr<float>, where dataset[i].vector = thrust::host_vector<float> When using an Array ...

Next.js sends requests before the component is actually rendered on the screen

I have the following code snippet: Routes: https://i.sstatic.net/7qlaV.png Inside my Home component located at app/page.tsx, I'm running the following: const HomePage = async () => { const games = await getGames(); return ( <div clas ...

Trouble with clicking buttons in Java and Selenium web scraping

Hey everyone, Currently, I'm working on a Java Selenium script that automates clicking and filling forms for me. I've written a line of code that's causing me some trouble. The intention is to click on a button, but it's not happening ...

AngularJS Routing misinterprets hash href from jQuery UI Datepicker

This issue is a result of my own oversight. I neglected to properly initialize the model for the datepicker, causing jQuery UI to prevent the navigation event from firing. If you're encountering this same problem, chances are there's another mist ...

Using Swift to decode JSON into a struct that includes searching for a string

I have been working with a JSON file obtained from a remote server, decoding it into a struct, and then making use of an @Published variable. Here's how: JSON: [{"keyword": "foo"}, {"keyword": "blah"}] Struct: ...

The method xxx is not defined within my ViewModel

Why am I encountering an error Uncaught TypeError: this.createRow is not a function when constructing the matrixLengthsAvailable array? The createRow function is defined at the end of my viewmodel... function TabBuyHarvesterModel() { self = this; ...

What could be causing worker threads to fail when instantiating a class from a separate file?

The following TypeScript file is being used: import { Worker, WorkerOptions, isMainThread, parentPort } from "worker_threads"; import path from "path"; export class SimpleWorker { private worker: any; constructor() { i ...

What is the best way to integrate nano.uuid into a series of promises that are fetching data from the database?

When working with express routing and nano, I encountered a challenge: router.get('/', function (request, response) { db.view('designdoc', 'bydate', { 'descending': true }) .then(results => { // data ...

What is the best way to conceal a conditional panel in a Shiny app using JavaScript when any action or button is clicked that is not one of the designated inputs

I am looking for a way to hide the conditional panel shown below whenever there is any user input that is not related to clicking the "Delete" button or selecting an option from the selectInput() function in the conditional panel, as demonstrated in the im ...

The Angular event handler fails to trigger change detection upon clicking

I am facing a simple problem where I have an element in a component's template with an ngIf condition and a (click) handler. Initially, the element is not rendered because the ngIf condition evaluates to false. What makes this interesting is that an ...