how to check if a specific data is present in an array using Vue

I am working with two arrays of data:

checked: [
'orange', 'apple', 'juice'
]

and the second array:

products: [
 '0': {
    title: 'this is product title',
    categories: [
     'apple', 'juice'
    ]
  }
]

I am trying to filter the data using a computed property with a checkbox.

Here is what I have tried so far:

computed: {
   filterProducts(){
       return this.products.filter(product => this.checked.includes(product.categories));
   }
}

However, the filter is not working as expected. Can anyone provide guidance on how to make this work?

Answer №1

If you're looking to accomplish this task, utilizing the .every() method is recommended.

Consider the following example:

checked = [
  'orange', 'apple', 'juice'
]

products = [{
  title: 'this is product title',
  categories: [
    'apple', 'juice'
  ]
}];

const filteredProducts = products.filter(({ categories }) => categories.every(cat => checked.includes(cat)));

console.log(filteredProducts);

With this code, you'll obtain an array of products that possess a categories array containing all its values present in the checked array.

If you're seeking to retrieve products with a categories array that consists of at least one value found in the checked array, opting for .some() instead of .every() would be more appropriate.

Answer №2

To determine if all items in an array of strings are present in another array, instead of using the .includes() method, you can utilize the .every() method on the product.categories array and check if each item is included in the checked array:

const checked = ['orange', 'apple', 'juice'];

const products = [
  {
    title: 'this is product title',
    categories: ['apple', 'juice']
  }
];

const filteredProducts = products.filter(product => product.categories.every(item => checked.includes(item) || !checked.length));

console.log(filteredProducts);

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

Fixing Cross-Browser Issues with the OnScroll Function

window.onscroll = function() { if( window.XMLHttpRequest ) { var bodyId=document.getElementById('bodymain'); if (bodyId.scrollTop > 187) { //make some div's position fixed } else { //mak ...

Harnessing the Power of JSON in Rails to Enhance Your jQuery UI Autocomplete Form

In the context of a rails application, I have been exploring different methods to fetch data from a JSON file. Despite my efforts, I have not been able to find a solution that suits my requirements. The static data I have is quite extensive, consisting of ...

Blur Event Triggered in Primefaces Editor

My current setup involves using JSF Mojarra 2.2.8 with PrimeFaces 5.1, where I utilize a PrimeFaces editor for text input. I am looking to automatically upload the entered text via ajax. However, the editor only supports an onchange event. I'm seekin ...

Loop through the AJAX response containing JSON data

Need assistance in extracting specific information from each hotel key and its rates within this JSON structure using JavaScript: [ { "auditData": { "processTime": "1545", "timestamp": "2016-04-08 04:33:17.145", ...

What is the best way to tailor my functions to apply only to specific objects within an array, instead of affecting them all?

I am facing an issue where my functions showMore and showLess are triggering for all objects in the array when onClick is fired. I want these functions to be called individually for each object. Both of these functions are responsible for toggling betwee ...

React Hamburger Menu not working as intended

I am facing an issue with my responsive hamburger menu. It is not functioning correctly when clicked on. The menu should display the navigation links and switch icons upon clicking, but it does neither. When I remove the line "{open && NavLink ...

Creating an automatic integer array ranging from 0 to 99: How it's done

Is there a method to automatically generate an integer array from 0 to 99? For example: int [] nums = new int[99]; I would like it to be in this format: int [] Nums = new int[] {0,1,2,3,4... ,99}; Thank you in advance! <3 <3. ...

Error occurs while running NPM script

My current task involves updating the dependencies of a React application. One of the key scripts in this app is defined in the package.json file, which is responsible for generating a message bundle for each locale. "scripts": { "build:langs": "NODE_EN ...

Unable to find / DELETE Express.js

Within my script, I am attempting to perform POST, GET, and DELETE operations. Whenever I use POST or GET, the correct messages are logged. However, whenever I attempt to use DELETE, I encounter the following error: Cannot GET /del_user The URL I have ...

What is the designated color for highlighting an option in Next.js?

This is my first time working on a Next.js project and I see an unfamiliar option. Which selection should I choose? I plan to use JavaScript for the Next.js project, not TypeScript. Just need to figure out which option is currently selected so I can pro ...

issue encountered when filling out a dropdown menu using a JSON data structure

Seeking assistance with populating a button dropdown in angularjs. Encountering the error message: "Unexpected end of expression: data.WotcSummary "|. Any ideas on what might be causing this issue? Here is the JavaScript file code snippet: WotcDashBoard ...

Concealing a label for a certain range of values

Does anyone have a clever solution for dynamically hiding a label associated with an input range element when the value is below a certain threshold? And then reappearing it once the value surpasses a specific minimum? Any thoughts on this matter? Thank ...

What is the process for deploying a next.js application with a custom express backend to a VPS or Heroku platform?

Does anyone have advice on deploying a next.js application with a custom express backend to either a VPS or Heroku? ...

Change the blue line to a crisp, clean white

Is it possible to customize the color of the blue line that appears when clicked? class Greetings extends React.Component { render() { return <div>Greetings {this.props.name}</div>; } } ReactDOM.render( <div> <p tabInde ...

The D3.extent() function is raising a TypeError because it is unable to iterate over the

I have been struggling with this issue for the past few hours, and I could really use some help. I'm not very familiar with using D3 in conjunction with React. Essentially, I have an anomaly detection algorithm running on the backend Flask App that r ...

The error message "Unexpected token var Node.js" means that there is a syntax error

Currently, I am dealing with Node.js and attempting to present a chart that is created from coordinates in a txt file uploaded to the server. However, I am facing an issue where everything works perfectly when I upload the file on the web page except for t ...

Ways to make JavaScript cycle through a set of images

I'm having trouble trying to set up a code that will rotate multiple images in a cycle for an image gallery I'm working on. So far, I've only been able to get one image to cycle through successfully. Any help or suggestions would be greatly ...

React/Ionic: Avoiding SVG rendering using <img/> elements

I seem to be encountering an issue when trying to load SVG's in my React/Ionic App. I am fetching weather data from OpenWeatherMap and using the weather?.weather[0].icon property to determine which icon to display. I am utilizing icons from the follow ...

The proper way to cancel useEffect's Async in TypeScript

I'm facing an issue with this straightforward example: useEffect(() => { axios.get(...).then(...).catch(...) }, [props.foo]) warning: can't perform a react state update on an unmounted component After some investigation, I found this ...

What is the significance of the ngf prefix within the context of AngularJS and ng-file-upload?

I recently discovered the ngf-select directive within ng-file-upload for AngularJS. Here's how it's used: <button type="file" ngf-select="uploadFiles($file, $invalidFiles)" accept="image/*" ngf-max-height="1000" ngf-max-size="1MB"> ...