1
const isEmpty = Object.keys(data).every((key) => {
  return data[key].length === 0;
});

How can I check if all arrays in objects are empty. Problem with this code I tried is that I get this:

data {
    0: Array[]
    1: Array[]
    2: Array[]
}
data {
    0: Array[]
    1: Array[1]
    2: Array[]
}

For first object I get false and that's okay but for the second I get true but I want to get false until all of arrays.length > 0, so I need to get true only for this situation:

obj {
    0: Array[1]
    1: Array[1]
    2: Array[1]
}
4
  • 1
    If you know that you want the following arrays.length > 0. Then why don't you use it instead of length === 0? Commented Feb 9, 2021 at 8:26
  • your data is completely invalid. What should Array[0] be? If that is really your code, that will not return false or true but just throw errors ... Commented Feb 9, 2021 at 8:27
  • What do you mean by writing Array[0] etc.? if you mean an array with 0 elements then your solution will give true for the first and false for the second, not false for the first and true for the second. Also, your desired result is unclear, you say you want it to be true until all of arrays.length > 0, but then say "I need to get true only for this situation", which suggests you want true only when all arrays.length's equal 1 Commented Feb 9, 2021 at 8:27
  • I created the solution Commented Feb 9, 2021 at 8:37

3 Answers 3

5

You could check the lenght of all values.

const isEmpty = data => !Object.values(data).every(({ length }) => length);

console.log(isEmpty({ 0: [], 1: [], 2: [] }));
console.log(isEmpty({ 0: [], 1: [1], 2: [] }));
console.log(isEmpty({ 0: [0], 1: [1], 2: [2] }));

Sign up to request clarification or add additional context in comments.

3 Comments

I think const isEmpty = data => Object.values(data).every(({ length }) => !length); otherwise the function should be named someEmpty or something like that.
naming is up to op. i would prefer hasEmptyArrays ...
Ah, you're right. I missed the fact that the desired behaviour doesn't match the name OP has given the function.
1

Use Object.values method.

Object.values(data).some(it => !it.length)

2 Comments

This will not work but you are close enough
@Rajesh sorry i forgot ! operator before it.length
0

The solution

function CheckArray(obj) {
  this.haveItems = false;

  this.onCheck = function (obj) {
    let createdArr = Object.values(obj);
    
    for (let i = 0; i < createdArr.length; i++) {
      if (createdArr[i].length > 0) {
        this.haveItems = true;
        break;
      }
    }
  };
}

let data = {
  0: [],
  1: [],
  2: [],
};

let a = new CheckArray();
a.onCheck(data);

console.log(a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.