Determine whether there is only one array in the object that contains values

At the moment, I am attempting to examine an array in order to determine if only one of its elements contains data. Consider this sample array:

playersByGender = {
  mens: [],
  womens: [],
  other: []
};

Any combination of these elements may contain data, with just one being filled out. Is there a way to check all three and generate a boolean value indicating if only one is populated?

I initially considered using a foreach loop, but it seems that this method cannot be applied directly to an object.

Any assistance or suggestions would be greatly appreciated. Thank you!

Answer №1

Loop through the object's keys using Array#reduce. If an array has a length greater than 0, increment the sum by 1. Finally, compare the final sum to return a Boolean value.

const playersByGender = {
  mens: [],
  womens: [1, 2],
  other: []
};

const onlyOne = (obj) => Object.keys(obj).reduce((sum, k) => obj[k].length > 0 ? sum + 1 : sum, 0) === 1;

console.log(onlyOne({
  mens: [],
  womens: [1, 2],
  other: []
}));

console.log(onlyOne({
  mens: [],
  womens: [1, 2],
  other: [1]
}));

Answer №2

let groupByAge = {
  young: [],
  old: [4,5],
  other: []
};

console.log(Object.values(groupByAge).filter(a => a.length > 0).length === 1);

Object.values is used to extract all values from the object, then we filter out non-empty arrays and count them using

.filter(a => a.length > 0).length

Answer №3

To achieve the desired outcome, it is recommended to utilize a for in loop instead of foreach. The for in loop allows you to iterate through the properties of your object, check the length of each array within the object, and determine if any of them have values.

Only 1:

var playersByGender = {
    mens: [1],
    womens: [],
    other: []
  },
  oneArrayLength = false;

for(var key in playersByGender) {
  if(playersByGender.hasOwnProperty(key)) {
    if(playersByGender[key].length) {
      if(!oneArrayLength) {
        oneArrayLength = true;
      } else {
        oneArrayLength = false;
        break;
      }
    }
  }
}

console.log(oneArrayLength);

More than 1:

var playersByGender = {
    mens: [1],
    womens: [1],
    other: []
  },
  oneArrayLength = false;

for(var key in playersByGender) {
  if(playersByGender.hasOwnProperty(key)) {
    if(playersByGender[key].length) {
      if(!oneArrayLength) {
        oneArrayLength = true;
      } else {
        oneArrayLength = false;
        break;
      }
    }
  }
}

console.log(oneArrayLength);

Edit:

The code has been adjusted based on the requirement mentioned, ensuring that the result is only true when exactly one of the arrays contains values.

Answer №4

If you want to iterate through arrays, determine their lengths, filter out those with none, and then calculate the count, there are multiple approaches available for achieving this goal. Various methods have been suggested by others, showcasing different ways of accomplishing the task. It is advisable to acquaint yourself with the array methods provided in JavaScript. Check them out here!

Here's an alternative method along with an explanation:

let arraysWithMoreThanOne = Object.keys(playerByGender).map(function(key) {
  // We start with an array of keys representing men, women, and other
  // Using the map method allows us to transform the key into something else,
  // like the length of the array
  // Only the array lengths are significant
  return playersByGender[key].length;
}).filter(function(count) {
   // The filter method helps eliminate items we aren't interested in
   // We only want those with more than one item
   return count > 0;
}) // By the end, we convert the object into a different result
.length; // This shows the number of arrays containing more than one item

In certain environments, additional support may be required for some methods.

Answer №5

To check if any of the arrays in playersByGender contain data, you can use a for..in loop like this:

function checkIfDataExists(arr) {
  var dataExists = false;
  for (var prop in arr) {
    if (playersByGender[prop].length) dataExists = true;
  }
  return dataExists;
}

var dataFound = checkIfDataExists(playersByGender);

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

Errors are encountered when attempting to use `usePathname()` and `useRouter()` functions. `usePathname()` returns null while `useRouter()` causes errors stating "NextRouter not mounted" and "invariant

I'm encountering an issue with implementing active navlinks in NextJS version 13.4.4. I need to access the current URL for this solution, but every attempt ends up failing. My folder structure is organized as follows: .next components Header header ...

toggle visibility of a div using AngularJS

Struggling to hide/show a div using AngularJS, I have gone through multiple tutorials with no success. Finally opted for the code snippet mentioned in this link, but still facing issues. Can anyone assist me in identifying the problem? PS: Using angular ...

Creating Eye-Catching Images by Incorporating Image Overlays Using Just One Image

I'm facing a bit of a challenge here. I need to figure out how to overlay an image onto another image using just a single image tag. Specifically, I want to add a resize icon to the bottom right corner of an image to let users know they can resize it ...

Custom AngularJS directive fails to reflect changes in model after selecting a file

I recently created a custom directive called ng-file-chosen, which is supposed to capture the selected file name from an <input> element and bind it to the ng-model passed in. In the code snippet below, the result of ng-file-chosen is linked to mode ...

Unable to execute jQuery - AJAX in PHP

Welcome_page.php <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#role").on("change", function() { alert($("#role").val()); var rol ...

Comparing the functionalities of C#, Python, and JavaScript, including rounding methods

There seems to be a difference in how decimal numbers are rounded in C# or Python compared to Javascript. I came across a solution for banker's rounding on Stack Overflow, but it doesn't work as expected in my scenario and leads to discrepancies ...

Typescript fails to identify the parameter type of callbacks

I am facing a challenge with the function below and its callback type: type Callbacks = { onSuccess: (a: string) => void; }; function myFunction(event: string, ...args: [...any, Callbacks]) { } The function works correctly except for one issue - ...

techniques for accessing HTML source code through an AJAX call

I am trying to retrieve the HTML source of a specific URL using an AJAX call, Here is what I have so far: url: "http://google.com", type: "GET", dataType: "jsonp", context: document.doctype }).done(function ...

Tips on optimizing website performance by implementing lazy loading for images and ensuring they are ready for printing

Many websites feature an abundance of images, prompting the use of lazy loading to enhance load times and reduce data consumption. But what happens when printing functionality is also required for such a website? One approach could involve detecting the p ...

What are the steps to achieve full screen mode in Google Chrome within an Angular 4 Application?

I'm working on an application and I'm looking to incorporate a feature where, when a user navigates from one component to another, the new component's ngOnInit method triggers the Chrome browser to enter full screen mode, similar to pressing ...

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...

POST requests in Angular Universal are making use of the IP address assigned to my server

My Angular Universal application (version 5.2.11) is currently hosted on Heroku, running on a Node server using express. I have implemented rate-limiters in all my POST routes to restrict requests by IP address, checking the request's IP through req.h ...

Unable to run for loop in vue.js

Hello, I'm a newcomer to using Vue.js and am encountering an issue with executing a simple for loop in my code. Any assistance or guidance would be greatly appreciated. Here is the snippet of my code: var Vue = require('vue'); Vue.use(requi ...

Using express.js to retrieve a JSON file via the command line

In need of assistance on how to retrieve a JSON file using express.js. My goal is to access it through the Mac terminal for a college assignment that involves creating an HTTP server acting as a basic data store. The requirements include responding to GET, ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

"Enhance User Experience with Material UI Autocomplete feature that allows for multiple

I am encountering an issue with a material ui auto component that I am currently working on. The component's code looks like this: <Autocomplete multiple options={props.cats} defaultValue={editRequest? ...

Instructions for creating a function that can receive an array of objects containing a particular data type for the value associated with the key K

Seeking guidance on how to define a specific signature for a function that accepts an array of objects and 3 column names as input: function customFunction<T, K extends keyof T>( dataset: T[], propertyOne: K, propertyTwo: K, propertyThird: K ...

Transformation of Ionic 2 ScreenOrientation Plugin

Can someone assist me with this issue? A while back, my Ionic 2 app was functioning correctly using the ScreenOrientation Cordova plugin and the following code: window.addEventListener('orientationchange', ()=>{ console.info('DEVICE OR ...

How can I simulate mouse position in a UIWebView?

Can the mouse position (x,y) for HTML-5 elements on a UIWebView be programmatically set using stringByExecutingJavascript in order to trigger hover, mouse over, and other interactions? ...

Ways to display a JSON object in CSV format

Is there a way to export a JSON object to a CSV file, where the sub-fields contain arrays of objects? I am unsure how to properly represent this embedded data in the CSV format. ...