2

Expected Input:

var arr = [null, 7, 9, undefined, 5, , 0, 8, 2, 1]
console.log(arr.length);

Expected Output:

Length: 7

3 Answers 3

1

You can do this way using filter(), it will filter out null and undefined but will keep 0.

var array = [null, 7, 9, undefined, 5, , 0, 8, 2, 1];
console.log(array.filter(n=> n == 0 || n ).length)

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

Comments

1

You can simply use .filter() method and Number.isFinite to get only numbers from array and ignore all falsy values except 0 like this:

var arr = [null, 7, 9, undefined, 5, , 0, 8, 2, 1]
arr = arr.filter(Number.isFinite);
console.log(arr);

Comments

1

You could iterate the items and check the value for counting.

var array = [null, 7, 9, undefined, 5, , 0, 8, 2, 1],
    length = 0;

for (let value of array) if (value !== null && value !== undefined) length++;

console.log(length);

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.