Algorithm
30 Days of JavaScript
Is Object Empty

2727. Is Object Empty

Tags

  • JSON

Link

https://leetcode.com/problems/is-object-empty/description/?envType=study-plan-v2&envId=30-days-of-javascript (opens in a new tab)

Question

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.
Constraints:
  • obj is a valid JSON object or array
  • 2 <= JSON.stringify(obj).length <= 105

Answer

JavaScript

/**
 * @param {Object|Array} obj
 * @return {boolean}
 */
function isEmpty(value) {
  if (Array.isArray(value)) {
    return value.length === 0;
  }
 
  if (typeof value === "object" && value !== null) {
    return Object.keys(value).length === 0;
  }
 
  return false;
 
  //   if (obj === null) return true;
  //   if (Array.isArray(obj)) return obj.length === 0;
  //   if (typeof obj === "object") return Object.keys(obj).length === 0;
  //   return false;
}
/**
 * @param {Object|Array} obj
 * @return {boolean}
 */
var isEmpty = function (obj) {
  return !Object.keys(obj).length;
  // return Object.keys(obj).length == 0;
  // return Object.keys(obj).length > 0 ? false : true
};
/**
 * @param {Object|Array} obj
 * @return {boolean}
 */
var isEmpty = function (obj) {
  if (JSON.stringify(obj).length <= 2) return true;
  else return false;
};