I'm working with JQuery to determine if an array, built earlier, with a determined number of indexes, is full or not. When created, array looks like this :
,,,,,,
All I want to do is find if every position is filled or not.
So bascially, i'm trying to test if and only if
[x,x,x,x,x,x]
For example, if
[x,x,x,,x,x] or if [x,,,,,] //return false, wrong...
Thanks a lot.
I'm working with JQuery to determine if an array, built earlier, with a determined number of indexes, is full or not. When created, array looks like this :
,,,,,,
All I want to do is find if every position is filled or not.
So bascially, i'm trying to test if and only if
[x,x,x,x,x,x]
For example, if
[x,x,x,,x,x] or if [x,,,,,] //return false, wrong...
Thanks a lot.
Share Improve this question edited Feb 10, 2010 at 15:52 pixelboy asked Feb 10, 2010 at 15:34 pixelboypixelboy 7291 gold badge13 silver badges37 bronze badges3 Answers
Reset to default 7You don't need any specific jQuery stuff to read the size of an array. Just vanilla javascript has what you need.
var arrayMaxValues = 4;
var testArray = [1,2,3,4];
if ( testArray.length == arrayMaxValues )
{
alert( 'Array is full!' );
}
else if ( testArray.length > arrayMaxValues )
{
alert( 'Array is overstuffed!' );
} else {
alert( 'There's plenty of room!' );
}
EDIT
Ah, you re-typed your question. So, you want to see if they array has zero null or undefined values?
function isArrayFull( arr )
{
for ( var i = 0, l = arr.length; i < l; i++ )
{
if ( 'undefined' == typeof arr[i] || null === arr[i] )
{
return false
}
}
return true;
}
If you fill your initial array with nulls, like:
const arr = Array(9).fill(null);
Then you can use some() or every() like this:
// check if a null doesn't exist
!arr.some(element => element === null)
// check if every element is not null
arr.every(element => element !== null)
Use whichever you like, since both of them breaks the loop when a null is found.
I know this is doing the same as Peter Bailey's function, but I only wanted to share it since it's a different approach using the built-in power of array filtering.
So, since the full array has a predetermined length you could filter it against 'undefined' and null and pare lengths, like this:
function isArrayFull(arr) {
return arr.length === arr.filter(function(o) {
return typeof o !== 'undefined' || o !== null;
}).length;
}