Requiring a condition for each element in an array which is part of an object

Let's discuss a scenario where I have to decide whether to display a block based on a certain condition.

Here is an example array structure:

const data = [
  { name: "item1" , values : [0,0,0,0,0]},
  { name: "item2" , values : [0,0,0,0,0]},
  { name: "item3" , values : [0,0,0,0,0]}
] // should return false

const data = [
  { name: "item1" , values : [0,0,0,0,0]},
  { name: "item2" , values : [0,1,0,0,0]},
  { name: "item3" , values : [0,0,0,0,0]}
] // should return true

The condition I need to check is that if all values inside the "values" array of each object are 0, then return false. If any value inside the "values" array is not 0, return true.

I attempted the following code, but it doesn't seem to work as expected:

const isZero = (currentValue) => currentValue === 0;
console.log(data.every(isZero));

Answer №1

To determine if all values in an array are true, you can examine the array and its values.

const check = array => array.some(({ values }) => values.some(Boolean));

console.log(check([{ name: "item1", values: [0, 0, 0, 0, 0] }, { name: "item2", values: [0, 0, 0, 0, 0] }, { name: "item3", values: [0, 0, 0, 0, 0] }])); // This will output false
console.log(check([{ name: "item1", values: [0, 0, 0, 0, 0] }, { name: "item2", values: [0, 1, 0, 0, 0] }, { name: "item3", values: [0, 0, 0, 0, 0] }])); // This will output true

Answer №2

To determine if the data object contains properties with values other than 0, you can use the .some method:

const data = [
  { name: "item1" , values : [0,0,0,0,0]},
  { name: "item2" , values : [0,0,0,0,0]},
  { name: "item3" , values : [0,0,0,0,0]}
] // returns false

const data2 = [
  { name: "item1" , values : [0,0,0,0,0]},
  { name: "item2" , values : [0,1,0,0,0]},
  { name: "item3" , values : [0,0,0,0,0]}
] // returns true


const verify = data => data.some(({ values }) => values.some(num => num !== 0));
console.log(
  verify(data),
  verify(data2)
);

Answer №3

To determine if there are any non-zero values in the 'values' member of each item in the 'data' collection, you can utilize the some method twice. First, apply it to the 'data' array, iterating over each item. Then, apply it again to each item's 'values' array to check if any value is not equal to 0:

data.some(item => item.values.some(v => v !== 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

Creating two variables that share an identical name

Can variables with the same name set outside of a function be called within the function? var a = $(window).width(); // This is the variable I want to call if(!$.isFunction(p)){ var a = $(window).height(); // Not this one alert(a); } FIDDLE ...

Tips for saving data to a file using the frontend

Is it possible for draw.io to write directly to a local file from my browser without the need for any server app or browser extension? I'm not referring to simply downloading a file, but actually writing to a file. For example, when creating a new dia ...

Struggling with setting up a PHP and Ajax registration and login system

Struggling with my code and in need of assistance. Desperately trying to set up a register form where users can input their username and password to sign up. Planning to utilize ajax, however, the integration seems faulty. For testing purposes, I tried ech ...

Export was not discovered, yet the names are still effective

There seems to be a slight issue that I can't quite figure out at the moment... In my Vue project, I have a file that exports keycodes in two different formats: one for constants (allCodes) and another for Vue (keyCodes): export default { allCodes ...

Ways to validate a foreign key in Strongloop?

I am faced with a situation where I have a collection of categories and a separate collection of places, with each place having a foreign key that corresponds to a category ID. You can find the list of categories in categorie.json: http://pastebin.com/ttu ...

Error: Ajax process terminated due to insufficient memory allocation

I'm facing an issue while submitting a simple form with minimal data. When I monitor the console tab, everything seems to be working fine with the AJAX URL. However, once the AJAX process is completed, an error alert pops up and the page redirects to ...

Instructions on deactivating the background when the sidebar is displayed and closing the sidebar by clicking anywhere other than the sidebar

I'm in the process of creating a sidebar for my website. When the sidebar is displayed (by clicking showRight), I want to disable the background content so that the user can't interact with anything outside of the menu. If the user clicks on th ...

Opting to utilize a multidimensional JavaScript array or object is a more efficient method

Here is a breakdown in JSON format: jsonResponse Folder 01 Product 01 - Folder 01 Product 02 - Folder 01 Product 03 - Folder 01 Folder 02 Product 01 - Folder 02 Product 02 - Folder 02 Product 03 - Fo ...

Ways to call a DIV element in a PHP file from a different PHP file

I am facing an issue with referring to a specific <div> element from one .php page to another. The current code is redirecting me to the home page of the first page, instead of displaying the desired content. Can anyone provide guidance on how to ach ...

Can a Stylus and Node.js with Express project utilize a local image?

Let's talk about using images in a Web app. In my Stylus file, style.styl, I typically set the image using code like this: .background background: url(http://path/to/image) But what if we want to save the image to our local app directory and use ...

Modify the input class once an image has been chosen (But not yet submitted)

Looking for a solution to update background image when file is selected <input type="file" class="imgupload" name="file" /> I've created image uploader with a hidden form element inside a padded div, displaying a background image. Want to chan ...

How to choose the option in one select box based on the selection in another, and vice versa

How can I dynamically select options in one select box based on the selection of another, and vice versa? I am using Ajax to redirect to a query page. while($result = mysql_fetch_assoc($query1)) { echo "<option value=".$result['username' ...

Display a progress bar on the index page of the grid view

Seeking assistance in displaying a progress bar on the grid view page index. Currently, I have successfully implemented a progress bar on button click and would like to replicate this functionality when the user switches from 1 to 2. Here is the modal pop- ...

The method element.isDisplayed() is indicating a false value even though the element is visibly present on the screen

element.isDisplayed() is returning false even though the element is visible on the screen, causing issues with clicking on it. I attempted to use the code below, but without success. Actions cursor = new Actions(driver); cursor.moveTo ...

What could be causing this Angular controller to throw the error message "Error: Unknown provider: nProvider <- n"?

Check out the jsFiddle code here: <div ng-app=""> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> {{data.message + " world"}} </div> </div> function FirstCtrl($scope) { ...

Adjust the color of the font within a div element when hovering over it

I've been attempting to modify the text color and add an underline when a user hovers over it. Despite trying various methods, I haven't been successful. I scoured the internet for a solution but couldn't find one that met my specific requi ...

Stop the Bootstrap accordion from collapsing when clicking on an internal anchor (href)

Is there a way to prevent the accordion from collapsing when opening a new page after clicking on a link? I have included the HTML code below, but I need assistance with the JavaScript to achieve this. I'm facing an issue where the accordion category ...

Calculate the total of the smallest values in three columns as they are updated in real-time

I'm facing an issue with dynamically adding the sum of the 3 lowest values entered in columns. The Total Cost Field is not displaying any value, and changing the type from number to text results in showing NaN. I've tried various approaches but h ...

Enhancing input value by incorporating selected options from multiple choices

I am working with 2 select boxes. <select id="field1" class="inputtextbox required" size="0"> <option value="Student">Student</option> <option value="Teacher">Teacher</option> <option value="Director">Director</optio ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...