Filtering an array in Vue using Lodash based on the values of another array

As I continue to learn JavaScript, I have encountered something that is confusing me.

Within my Vue data object, I have the following properties:

  data: {
    allergenFilter: [],
    categoryFilter: [],
    results: {},
  },

I am using an array of checkboxes to select allergens for products, which then populates my allergenFilter Vue property like this:

[
  0: "nut-free",
  1: "milk-free"
]

Additionally, I have a list of allergens that a product may or may not have, and I want to filter products based on these choices. Here is an example of allergens from a product:

[
  0:"vegetarian"
  1:"vegan"
  2:"egg-free"
  3:"nut-free"
]

I attempted to filter the results by using the following code:

  this.results.filter(result =>
    result.allergens.includes(
      this.allergenFilter
    )
  )

Unfortunately, this approach didn't work due to the mismatch in key-value pairs. I understand the issue, but I am uncertain about how to determine if the values in one array are included in the values of another array.

Answer №1

To improve your code, consider implementing another nested loop to check if any of the allergens are present in the allergenFilter.

this.results.filter(result =>
    result.allergens.some(
        allergen => this.allergenFilter.includes(allergen)
    )
)

If you require that all allergens in allergenFilter must be present, use .every instead.

this.results.filter(result =>
    this.allergenFilter.every(
        allergen => result.allergens.includes(allergen)
    )
);

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

What is the best way to insert a new value into an already existing JSON array?

My JSON structure looks like this: { "intents": [ { "tag": "greeting", "patterns": [ "Hi there", "How are you", ...

Display a preview window once the image has been chosen

I have created an image preview div to show the selected image's thumbnail. Everything was working fine so far. But now, I want this div to be hidden when the page initially loads and only become visible when a user selects an image to upload. Here is ...

Retrieve data from an online JSON file

I am still learning about working with json and would appreciate some guidance. The data file I need to access is located at this url - I would like to display it in the following format: <ul id="smenu"> <li></li> </ul> Cou ...

Run a JavaScript function multiple times in the code behind using C#

My challenge involves using a datatable and executing a JavaScript function for each row, with different values each time. For every row, the JavaScript function is executed and the result is sent back to the code behind using a web method. However, with ...

The Three.js loading bar fails to disappear after the model has finished loading

I have created a page that is inspired by this example and have incorporated relevant lines from the webgl_material_bumpmap example to implement a loading progress Dom Element. You can view the page (temporarily) here. If the information provided below is ...

Issues arising from data representation on the user interface using AngularJS

Below is a JSON sample containing 2 objects that I am fetching: [{"project_id":"538","proyecto":"Caja","tarea":"DEF","fecha_termino":"00-00-00","estado":"Vencido","nombre_completo":"Christiano Ronaldo","alerta":"-Analista responsable: Lionel Messi.; &bsol ...

Having trouble changing the icon in Google Maps during the event?

Seeking guidance with Google API V3 as a newcomer. The task at hand is to switch the icon during a zoom event. Everything works smoothly except for the part where I need to detect the change in zoom and modify the icon from a basic circle to Google's ...

Having trouble installing dependencies in your Vue project?

I recently encountered an error while running the npm i command on our Vue project to install all node packages. I'm not sure what this error means or how to resolve it. https://i.stack.imgur.com/rP2iU.png ...

Click the Button to Trigger Database Update

I have been struggling with updating a dynamic table that allows inline editing and dynamically adding rows. My goal is to click a save button that triggers an UPDATE query to modify the database. Unfortunately, I can't seem to figure it out on my own ...

Unable to append XML nodes using jQuery's parseXML function, but able to append font

Jquery : $.get("config.xml",function(xml){ $(xml).find("config").find("images").append("<image><url>../demo/Headline/2012/12/20/0/0/A/Content/8/Web201212_P8_medium.jpg</url><name></name><redirect>none</r ...

Invoke a function from the main program and transfer an array from one class to another

Having difficulty with static methods and passing arrays. Any suggestions on how to call this method? How can I pass the array to another class for editing? Appreciate any help you can provide. import java.util.Scanner; class getArray { public st ...

Converting a 3D image array in NumPy to a 2D array

I am working with a 3D-numpy array representing a grayscale image. Here is an example of how it looks: [[[120,120,120],[67,67,67]]...] Since it is a gray image, having every R, G, and B value the same is redundant. I am looking to create a new 2D array t ...

Turning off devtools in Next.js

Currently, my focus is on developing an application using Next.js and I am in search of a way to prevent the opening of devtools. While exploring npm packages, I came across a promising tool called Disable-devtool - npm link. However, Next.js keeps present ...

What is the proper way to indicate the pointer to the current element within the array?

How can I modify a code that displays a list of posts? import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX []; } export class Compone ...

Learn how to showcase a text file uploaded to a webpage with NODE js and HTML

<!DOCTYPE html> <html> <body> <form action = "/submit" method = "post"> Select a file: <input type="file" name="file"> <input type="submit"> </form> </bod ...

Using PHP to dynamically change the title of a Bootstrap modal

I've been attempting to dynamically update the title of my modal using PHP. The title I wish to display is stored in a variable and is being reassigned based on user input. Below is my PHP code snippet: $studentName = $results['Studentname&apo ...

How can I implement conditional rendering with React on a div element?

Is it possible to implement conditional rendering by simply adding the boolean checked isVisible=true onto the div? Will this ensure that it only renders when true? Could there be any potential issues with the component's state changing after renderi ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

Determine the orientation of the object relative to the camera in threejs

I am currently facing a scenario where I need to determine the direction of an object in relation to the camera. While I have methods for detecting if an object is within the camera's view, I am now tasked with determining the directions of objects th ...

Sort object keys in a Vue component by the English representation of numbers in descending order

I've got some data for a dropdown menu. The list is currently in a random order, but I'd like to arrange it in descending order based on the key values (One, Three, Five, ...). new Vue({ el: '#app', data: { data: { Abc: ...