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.
Input: obj = {"x": 5, "y": 42}
Output: false
Explanation: The object has 2 key-value pairs so it is not empty.
Input: obj = {}
Output: true
Explanation: The object doesn't have any key-value pairs so it is empty.
Input: obj = [null, false, 0]
Output: false
Explanation: The array has 3 elements so it is not empty.
/**
* @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
}
};
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`.