Ways to verify the presence of an empty array object

I'm trying to determine whether all arrays inside an object are empty. To illustrate, consider the following object:

var obj = {
   arr1: [0, 1, 2],
   arr2: [1, 2, 3],
   arr3: [2, 3, 4]
};

After pop()ing values from the arrays within the object, I need to verify if they are all empty.

One approach I've considered involves the following code snippet:

var isEmpty = true;
for (var item in obj) {
   if (obj[item] !== 0) {
      isEmpty = false;
   }
}
// now isEmpty accurately indicates whether all arrays in the object are empty

However, I'm curious if there's a simpler and more direct solution available. I've searched for alternatives but answers like this one don't apply because it focuses on checking if the object itself is empty rather than the arrays within the object. My question is essentially the opposite of this one.

Answer №1

To determine if all arrays are empty in an object, you can loop through the values and check their lengths.

const areAllArraysEmpty = obj => !Object.values(obj).some(({ length }) => length);

console.log(areAllArraysEmpty({ a: [], b: [], c: [] }));   //  true
console.log(areAllArraysEmpty({ a: [1], b: [], c: [] }));  // false
console.log(areAllArraysEmpty({ a: [], b: [1], c: [] }));  // false
console.log(areAllArraysEmpty({ a: [1], b: [2], c: [] })); // false

Answer №2

To check if all arrays within an object are empty, you can utilize the every method:

var obj = {
   arr1: [0, 1, 2],
   arr2: [1, 2, 3],
   arr3: [2, 3, 4]
};

const hasEmptyArrays = obj => 
  Object.values(obj).every(arr => arr.length === 0)

console.log(hasEmptyArrays(obj))

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

Having trouble utilizing a function with an async onload method within a service in Angular - why does the same function work flawlessly in a component?

I successfully created a component in Angular that can import an Excel file, convert it into an array, and display its content as a table on the page. The current implementation within the component looks like this: data-import.compoent.ts import { Compo ...

set ajax url dynamically according to the selected option value

My form features a select box with three distinct choices <select id="tool" name="tool"> <option value="option1">Option1</option> <option value="option2">Option2</option> <option value="option3">Option3</ ...

How can I fetch data from another table by querying array values in Postgresql?

I have recently started working with a database that includes an array field (Phones) containing IDs from another table. I am new to this feature and I am wondering how I can retrieve all the records from the Public_Phone table that are associated with the ...

Reordering React Lists: Showcasing the Latest Addition on Top

I'm currently working on a React list and keys project. I want the latest item added to appear at the top. Can anyone offer some assistance with this? For example: import { useState } from "react"; function ListsKeys() { const [names, set ...

Looking to conceal the edges of a ThreeJS box primitive

I'm trying to figure out how to hide the edges displayed in a box primitive using ThreeJS. The edges only appear when I apply a texture to the faces. I've attempted various options such as setting wireframe=false, but the edges persist. Here&ap ...

Maintain the selected bootstrap tab even after the page is refreshed, even when the content is loaded dynamically

I am currently facing an issue with loading tabs using Angular. Whenever a tab is clicked, the id is saved to localStorage. Now, I want to programmatically click on the same tab using jQuery when the page refreshes. However, since the DOM element for the ...

Angular: merging animations with scope updates

If you're curious to see some code, check it out here: some code My inquiry pertains to using Angular to blend a change in data triggered by a click with a fade in/fade out animation. I've managed to implement content changes on click and anima ...

The JavaScript button's onClick event is not functioning properly, despite the method executing normally

I'm currently working on creating a button using JavaScript that, when clicked, will trigger an AJAX request to some PHP code. Interestingly, I have already set up three buttons with the same functionality and they are all functioning perfectly. Wha ...

jquery is unable to locate text

UPDATE: I have recently implemented a function that calculates and displays the length of a certain element, but it currently requires user interaction to trigger it: function check() { alert($("#currentTechnicalPositions").html().length); } After s ...

Using HTML and JavaScript to implement a dragging functionality on a canvas element

After creating a square grid using HTML canvas, I've added a drag feature that allows users to draw rectangles by dragging over the grid. However, it seems that non-rectangle shapes can also be drawn in certain cases. Let's delve into an additio ...

NodeJS MySQL failing to retrieve the most updated data post-write

I'm struggling to solve an issue where after performing data operations (create, update, delete) and then querying for the data afterwards, I receive the previous version of the data rather than the updated version. For example: Let's say I hav ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

JavaScript encoding the text

Looking for a straightforward JavaScript function to encrypt text data from a textarea using a key (the key being the user's password stored as a hashed session variable, outputted by PHP into a field). The objective is to have the content of the tex ...

Reorganizing Elements within an Array using JavaScript

Imagine I have the characters: H, M, L I want to create sorted arrays like this: var array1 = [ "H", "M", "L", "L", "M", "H" ]; My goal is to avoid having more than one unique character in the first three and last three characters when using the shuffl ...

When I try to post using the raw feature in Postman in Node.js, the post ends up empty

My API is supposed to receive data for saving in the database. However, when I call the PUT method, my req.body.nome returns empty. It works fine with form-urlencoded, but I've tried using body-parser and it's deprecated. Here is my request usin ...

Issue with the functionality of array.push in JavaScript when used with Angular ng-repeat

In other parts of my application, I have a similar code snippet that works perfectly fine. The issue arises when pushing an object into an empty array and using ng-repeat in the view. This is the JavaScript code: $scope.upload = $upload.upload({ url ...

JQuery post request not providing the expected response after posting

I have a post request var prodId = getParameterByName('param'); var pass = $('#password1').val(); $.post("rest/forget/confirm", { "param" : prodId, "password" : pass }, function(data) { ...

An unanticipated issue has occurred: TypeError - the product information being searched for is not defined

import { useContext, useEffect, useState } from "react" import Layout from "../components/Layout" import { ProductsContext } from "../components/ProductsContext" export default function CheckoutPage(){ const {selecte ...

SQLite Simplified - A Primer on Fundamentals

I'm currently experimenting with the SQLike query engine from Thomas Frank's website and finding it difficult to grasp the basic concept. In my project, I have JSON data sourced from my PHP code, which is structured like this: var placesJSON=&l ...

Invoking a shared controller function in AngularJS from a separate controller

My main objective is to retrieve the current logged-in user by calling back to the server when a visitor lands on the site while still logged in. The challenge I face is determining which controller will be active since it's uncertain which page the v ...