Is Object Empty | #2727 | LeetCode | JavaScript Solution

Author: neptune | 01st-Sep-2023

Problem : Is Object Empty | #2727 | LeetCode

Given an object or an array, return if it is empty.

  • An empty object contains no key-value pairs.

  • An empty array contains no elements.

You may assume the object or array is the output of JSON.parse.


Example 1:

Input: obj = {"x": 5, "y": 42}

Output: false

Explanation: The object has 2 key-value pairs so it is not empty.

Example 2:

Input: obj = {}

Output: true

Explanation: The object doesn't have any key-value pairs so it is empty.


Example 3:

Input: obj = [null, false, 0]

Output: false

Explanation: The array has 3 elements so it is not empty. 

Solution:

    /**

     * @param {Object | Array} obj

     * @return {boolean}

     */

    var isEmpty = function(obj) {

        if (Array.isArray(obj)){

            return obj.length === 0;

        } else if (typeof obj === 'object'){

            return Object.keys(obj).length === 0;

        }

        else{

            return false

        }

    };



Explanation:

This function first checks if the input is an array and then checks if its length is zero. If the input is not an array, it checks if it's an object (and not null) and then checks if the number of keys in the object is zero. If it's not an object or an array, it returns `false`.



👉 Read More
Generate Fibonacci Sequence - JavaScript | Hackerank
Managing Virtual Environments in React JavaScript Projects
To Be Or Not To Be | #2704 | LeetCode Solution
Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Function Composition | #2629 | LeetCode Solution
Counter | #2620 | LeetCode Solution
Different ways to handle state in React applications
Chunk Array | #2677 | LeetCode Solution
Counter 2 | #2665 | LeetCode Solution
Array Reduce Transformation | #2626 | LeetCode Solution
Add Two Promises | #2723 | LeetCode Solution
Filter Elements from Array | #2634 | LeetCode Solution
Arrow Functions in JavaScript | ES6
From REST to GraphQL: The Future of API Design
How I Built My Blogging Website Using React, Node.js, and Jamstack Architecture?
How to Perform Unit Testing in React Components with Examples?
Do you know ! How to manage State in Functional & Class Components in React ?
A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
How to Get Started with Jamstack: A Comprehensive Guide?
Why, What, and When: Understanding Jamstack?
Explore more Blogs...