How do I check whether a nested array is empty or not? The array looks like this when there is no data:
const data = [ [ ] ]
And if it has data it looks like this:
const data = [
[{"Product": 7 }]
]
To check if it is empty I am doing the following which does not work:
if (!Array.isArray(data[0][0]) || data[0][0].length === 0) {
return "Data is empty"
}
What I don't understand is why !Array.isArray(data[0][0]) returns true, which means the nested array is not an array (which is strange because it is an array, just empty). According to the docs, Array.isArray([]) returns true so how can !Array.isArray(data[0][0] return true?
The data[0][0].length part throws an error saying "TypeError: "data[0][0] is undefined"". Why would that be the case?
That leads to the question of how to check if a nested array is empty or not?
You could do something like this:
function checkIfEmpty(array) {
return Array.isArray(array) && (array.length == 0 || array.every(checkIfEmpty));
}
console.log(checkIfEmpty([[{"name":"something"}]])); // false
console.log(checkIfEmpty([[]])); // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With