0

It is possible to validate an array like this:

const Array = [[1, 2], ['hello', 'hi'], []]

I need to kwon when one array is empty or is ".length === 0" but only if one of the array is empty it say an error and if all are empty is the same error.

for example this is an error

const Array = [[1, 2], ['hello', 'hi'], []]
const Array = [[1, 2], [], []]
const Array = [[], ['hello', 'hi'], []]

when all array has values then do something else like show an alert

2
  • 1
    Array.prototype.some or the version for the negation, Array.prototype.every, are your friends. Commented Mar 19, 2021 at 0:33
  • 1
    You cannot redeclare a const, which shouldn't be Array anyways, since Array is a predefined constructor. Commented Mar 19, 2021 at 0:36

5 Answers 5

1

You can use the .some() function to check if one or more items of an Array matches a certain condition. Here is what it would look like applied to your specific case:

const array_of_arrays = [[1, 2], ['hello', 'hi'], []]

let contains_empty_arrays = array_of_arrays.some((sub_array) => sub_array.length === 0)

console.log(contains_empty_arrays )

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

Comments

1

Using Array.prototype.every()

const data = [[], ["hello", "hi"], []],
  check = data.every(item => item.length);
if (!check) {
  alert("Empty Values");
}

Comments

0

You can do something like this.

const myArray = [[1, 2], ['hello', 'hi'], []];

if (myArray.find((innerArray) => innerArray.length === 0)) {
  console.log("Some error")
} else {
  console.log("Do something else");
}

Comments

0

Can you please try running the snippet below:

const myArray = [[1, 2], ['hello', 'hi'], []];

var with_empty = false;

for (i = 0; i < myArray.length; i++) {

  if(myArray[i].length == 0){
    with_empty = true;
    break;
  }

}

if(with_empty)
  alert('There is an empty value!');

Comments

0

Maybe you want to do something like:

function fullNest(arrayOfArrays){
  for(let a of arrayOfArrays){
    if(!a.length){
       return false;
     }
   }
   return true;
}
const nest = [[1, 2], ['hello', 'hi'], []];
console.log(nest); console.log(fullNest(nest)); console.log('-'.repeat(50)); 
nest[2].push('full now'); console.log(nest); console.log(fullNest(nest));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.