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

Exploring the PayPal Checkout JavaScript SDK's CreateOrder call and interpreting the response

I am currently exploring how to use the JavaScript SDK to display PayPal payment buttons on a website. I am new to working with JSON and REST API calls, so I am facing some challenges in implementing this. The createOrder function is running smoothly and ...

Harnessing the power of lazysizes with WebP

I've been working on optimizing our site through the Google Lighthouse audit, and it's clear that images are a major focus. Right now, my main goal is to address the issue of 'Deter offscreen images' highlighted in the audit. To tackle ...

Switch between two AppBars simultaneously while scrolling in Material UI

In my Header.js component, I have two AppBars. The first one is sticky and the second one is not initially visible. As we scroll down, I want the second AppBar to collapse and the first one to stay stickied at the top of the screen. I looked at the Materi ...

Utilizing BBC gelui within Joomla 3.0 for seamless integration

I am currently using Joomla! 3.0 with the Joomlashape Helix template and I am following a tutorial. You can check out the tutorial here. The tutorial mentions that I need to download RequireJS. Can anyone confirm if RequireJS is compatible with Joomla 3 ...

Ways to resolve the issue of data not displaying on the page, even though it appears in the

I am attempting to upload an image that has been converted to a URL using Ajax. The issue I am facing is that $image = $_POST['imgData']; does not display anything, but when I check the developer tools in the network preview, the data can be seen ...

Looking for a way to easily swipe through videos?

My mobile phone viewport displays a series of pictures and videos, with the swipeleft/right function enabled for browsing. However, I noticed that while the swipe feature works fine for images, it stops functioning when a video is displayed. Can anyone p ...

React-Redux is throwing a TypeError due to its incapability of reading the property 'map' which is undefined

I'm still fairly new to diving into React and Redux, and I find myself a bit puzzled. My main objective is to populate HTML with a plethora of JSON data through GET requests. Utilizing react and redux to control the state of these objects, however, i ...

"Interactive Connect 4 Game in Javascript - Drop the disk into the bottom row of the chosen

Check out this awesome Connect4 game I found: http://codepen.io/anon/pen/lmFJf I have a specific goal in mind for the game. When I click on an empty space in any column, I want it to automatically drop into the lowest available spot in that column, follow ...

Issues encountered with integrating external jQuery/JavaScript functions with Wordpress child theme template

After creating a custom template in my WordPress child theme, I added a link to the Bootstrap v3.0.3 .js file stored on my site. While the popup modal is functioning properly, the jQuery tabs seem to be having some issues. Although they are being display ...

javascript issue with onchange query

The JavaScript snippet below is included in the head section of my file. <?php echo "<script language='JavaScript'>\n"; echo "var times = new Array();\n"; echo "times[0] = 0;\n"; foreach($times as $time) { echo "times[". ...

What is the process of accessing JSON data transmitted from a Express server in JavaScript?

Working with a node server, I've set up a client-server model, meaning the client connects to "localhost" and express generates a response based on certain logic. While I'm able to send a JSON object through the response, I'm unsure of how t ...

Executing a JavaScript function using document.write()

When I try to click on the SWF part1 links within the document.write() function in order to call the openswf function, nothing happens. Here is my code: <html> <a href="#" onclick="Popup();">show popup</a> <script> functio ...

Obtain URL parameters prior to rendering with Next.js on the server side

Looking to retrieve the parameters from a URL coming from the Spotify API, for example: http//link.com/?code=examplecode. Is there a way to extract the value of "code" prior to rendering so that I can redirect it and transfer the code value to another p ...

What is the best way to align content in the left center of a Paper component and ensure it stays that way on smaller devices?

Recently, I've been developing a component for my Goal Sharing social media platform. Here's what I have accomplished so far: https://i.stack.imgur.com/UDRim.png In an attempt to position the Avatar component along with two typography component ...

When trying to upload numerous files, only a single file ends up being

The issue is with the function that is only uploading 1 file instead of all 6 files. It seems to be returning an array $fileDirectories with a dimension of 1, whereas I expected it to have 6 dimensions. The interesting thing is that count($_FILES['fil ...

Utilizing Angular controllers to access data attribute values from child elements

Today I embarked on the journey of learning AngularJs through online tutorials. Excited about my new project, I started working on creating some useful features using Angular. Here is a snippet of my progress so far: The HTML Part <div data-ng-control ...

Managing input/output requests on Amazon EC2 instances

Having mastered node, javascript, and other technologies the hard way, I am finally on the brink of releasing my debut web application. After signing up for Amazon Web Services and setting up a micro instance to take advantage of the first year's free ...

Encountering issues with Next.js routing - Pages failing to load as expected

Having some trouble with the routing in my Next.js application. I've created a page named about.tsx within the "pages" directory, but when trying to access it via its URL (localhost:3000/about), the page fails to load correctly and displays: This Pa ...

Display a concealed text box upon clicking BOTH radio buttons as well as a button

Below is the HTML code for two radio buttons and a button: <body> <input data-image="small" type="radio" id="small" name="size" value="20" class="radios1"> <label for=&qu ...

Adding an arrow to a Material UI popover similar to a Tooltip

Can an Arrow be added to the Popover similar to the one in the ToolTip? https://i.stack.imgur.com/syWfg.png https://i.stack.imgur.com/4vBpC.png Is it possible to include an Arrow in the design of the Popover? ...