Reputation: 835
I want to check if an object has only empty arrays left. Here is an example of the object:
var obj = {
arr1: [0, 1, 2],
arr2: [1, 2, 3],
arr3: [2, 3, 4]
};
I have been pop()
ing off values from the arrays inside the object and then I need to check if all of the arrays are empty.
One method I have thought of is like so:
var isEmpty = true;
for (var item in obj) {
if (obj[item] !== 0) {
isEmpty = false;
}
}
// now isEmpty reflects the state of all the object's arrays being empty
However, I am wondering if there is a more simple and straightforward solution. I've looked around and answers like this don't work because the object isn't empty, the arrays inside of the object are. My question is kind of the inverse of this one.
Upvotes: 0
Views: 54
Reputation: 15461
You can use every
method on the object values:
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))
Upvotes: 2
Reputation: 386578
You could get the values and check each array with their length.
const areAllEmpty = object => !Object.values(object).some(({ length }) => length);
console.log(areAllEmpty({ a: [], b: [], c: [] })); // true
console.log(areAllEmpty({ a: [1], b: [], c: [] })); // false
console.log(areAllEmpty({ a: [], b: [1], c: [] })); // false
console.log(areAllEmpty({ a: [1], b: [2], c: [] })); // false
Upvotes: 2