Convert the object containing arrays to a boolean value, which will be true if at least one of the arrays is not empty

Here's the scenario:

searchCriteria: {
  filter1: [?],
  filter2: [?],
  filter3: [?],
  and so on
}

I am aiming for a boolean output that indicates whether any of the filter arrays contain data (i.e. are not empty).

Something along the lines of:

const hasDataInFilters = Object.values(searchCriteria).reduce(...);

What method would be most effective in achieving this?

Answer №1

.some is the better choice here, as it checks if any of the elements in the values array meet a certain condition.

const hasActiveFilters = Object.values(filters).some(array => array.length);

Answer №2

To determine if any of the arrays in the filter fields are not empty, you can utilize the Array.some method:

const data = {
  filters: {
    field1: [],
    field2: [],
    field3: [],
  }
}

const hasActiveFilters = (filters) => Object.values(filters).some(value => value.length > 0)

console.log(hasActiveFilters(data.filters))

data.filters.field2.push('xyz')

console.log(hasActiveFilters(data.filters))

Answer №3

Give it a shot with .some()

const criteria1 = {
  cat1: [],
  cat2: [],
  cat3: undefined
}
const criteria2 = {
  cat1: undefined,
  cat2: undefined,
  cat3: []
}
const criteria3 = {
  cat1: [4, 5, 6],
  cat2: [7],
  cat3: {}
}
const hasSize = y => y && y.length;
const hasCriteria1 = Object.values(criteria1).some(hasSize);
const hasCriteria2 = Object.values(criteria2).some(hasSize);
const hasCriteria3 = Object.values(criteria3).some(hasSize);
console.log(hasCriteria1); // false
console.log(hasCriteria2); // false
console.log(hasCriteria3); // true

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

Error: Unable to retrieve data through Ajax request

$(document).ready(function(){ /* Fetching Data from TTC for Union Station */ $.getJSON("http://myttc.ca/Union_station.json?callback=?", function(data){ if (routes.length > 0) { // Display the stop details with departur ...

Customizing line charts with D3.js and AngularJS for ultimate visual impact

Working on a project involving the creation of a line chart using D3.js library and AngularJS within an Ionic framework. I am looking to customize the color of data points based on the Y-axis values. For example, if the value falls between 0-30, I want t ...

Displaying threaded discussions in React

Below is an array that contains comments, and I am attempting to display them in a threaded manner by utilizing the parentId property. comments: [ { id: 1, parentId: null }, { id: 2, parentId: 1 }, { id: 3 ...

What is the reason behind the undefined value of "this" in this particular class method?

I have scoured the depths of the internet in search of a solution, but I am still grappling with an issue related to a JS class I am developing for a Micro Service (still learning as I go). When attempting to call a method within a class on an instantiate ...

Preserving intricate nesting in a Mongoose schema

I've encountered a problem when trying to save nested subdocuments - I'm not certain if it's because they're not in an array or some other reason. The docs suggest that nested objects should be auto-saved, but that doesn't seem to ...

Adjust the package.json file for deployment

I've encountered a problem while attempting to deploy my nodejs application on Heroku. Despite following the documentation and modifying files in the root directory, I have not been successful. Below is the structure of my package.json file: { ...

How does Chrome have the capability to access the gist json file? Isn't that typically not allowed?

Fetching a JSON file from Github Gist can sometimes be straightforward, but in certain situations, I have faced difficulties due to CORS restrictions. This has led me to resort to using JSONP instead. Can you shed some light on why this is the case? ...

Unexpected JavaScript Bug (with jQuery)

I have an interesting code snippet that captures button clicks and then hides the existing content, revealing the content of the clicked item instead. This code is part of my init.js file along with other functionalities: $(function() { $('#conta ...

The script functions perfectly in jsfiddle, yet encounters issues when used in an HTML

I stumbled upon a seemingly peculiar issue with my script in jsfiddle: https://jsfiddle.net/oxw4e5yh/ Interestingly, the same script does not seem to work when embedded in an HTML document: <!DOCTYPE html> <html lang="en"> <head> & ...

What methods does GitHub use to determine my login status?

I removed the localStorage storage, but it didn't make a difference. I'm curious - does GitHub store IP addresses of logged-in users in a database, or maybe in browser headers? ...

The interactions and functionalities of jQuery sortable and draggable elements

Looking for some assistance with a project involving draggable objects 'field' and 'container', along with a sortable object 'ui-main'. The goal is to drag the two aforementioned objects into 'ui-main', while also al ...

What is the process for importing data from a text file into the scheduling application?

Due to time constraints, I need to import a specially formatted text file for the scheduler. To expedite the process, I am seeking assistance with understanding the format for future reference. The file is structured as follows: 2 0 1 3 5 4 t 1 3 6 7 3 6 ...

How do you incorporate ScrollTop animations using @angular/animations?

I'm attempting to recreate the animation showcased on Material.io: https://i.stack.imgur.com/OUTdL.gif It's relatively easy to animate just the height when clicking on the first card in the example above. The challenge arises when you click on ...

Is it possible to duplicate this jQuery/Javascript feature using PHP?

I have the code to fetch tweets in JavaScript, but I need it converted to PHP. Can anyone provide any guidance on how to achieve this? $(document).ready( function() { var url = "http://twitter.com/status/user_timeline/joebloggs.json?count=1 ...

Top way to include an HTML and javascript file in an Ext.Panel within Sencha Touch

My main goal is to efficiently include external HTML files and display them on an Ext.Panel in Sencha touch 2.3 by creating a wrapper module for the HTML file that can be instantiated using xtype, with an external Javascript file for event handling. Updat ...

What causes JavaScript parseFloat to add additional value in a for loop implementation?

I am facing a challenge where I need to convert an array of strings into an array of decimal numbers. The original array of strings is structured like this: var array = [" 169.70", " 161.84", " 162.16", " 176.06", " 169.72", " 170.77", " 172.74", " ...

Problem with targeting the .prev() and closest() class of a text input box

Could you please review This Demo and advise why I am unable to select the first .fa class before the text box #name ? This is what I have been trying: $(this).prev().closest(".fa").addClass("err"); within this code block <div class="row"> & ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

Using Python's numpy library, generate a two-dimensional array of values by utilizing the coordinates, then visualize the data by plotting it with pcolormesh or

I have two arrays containing Latitude (Lat) and Longitude information, both of which are 1D arrays with a shape of 5. Additionally, I have another array labeled C, also a 1D array of shape 5. My goal is to create a heatmap plot using pcolormesh. Below is ...

Turn off the feature of map scrolling on OpenStreetMaps

Is there a way to prevent mouse interactions and scrolling in an open maps iframe? I have already tried adding the attribute scrollwheel="false" to no avail. Are there any CSS methods to achieve this? <iframe id= "mapsource" scrollwheel="false" src="ht ...