0

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.

Elijah Mock
  • 587
  • 8
  • 21
  • Interesting question. Here's a very non-simple and very non-straightforward solution, that actually works: `var totalLength=0; for(item of JSON.parse(JSON.stringify(obj).split("{").join("[").split("}").join("]").split(":").join(","))) if(item.length==0) totalLength+=item.length; console.log("obj's arrays are "+(totalLength?"Not":"")+"empty");` – iAmOren Jun 27 '20 at 17:55

2 Answers2

2

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
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

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))
SLePort
  • 15,211
  • 3
  • 34
  • 44