1

I have an array like this below

const userArray = ['school', 'science', '', '', null, 'bachelors', 'final', undefined, null]

As you can notice, i have 2 empty string, 2 null and 1 undefined in it. So the total is 5.

how can i loop through each time and still get total count of empty string, null and undefined in the array.

0

2 Answers 2

3

You can use Array filter.

const userArray = [
  "school",
  "science",
  "",
  "",
  null,
  "bachelors",
  "final",
  undefined,
  null,
];
let ret = userArray.filter((x) => !x).length;
console.log(ret);

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

6 Comments

can you also specify please how did u find out null "" and undefined. How does !Boolean(x)) || [] help for this
when casting null, undefined and empty string to boolean its always returns false and I used empty array if there is no boolean false item it will return zero.
@RaviK || [] isn’t part of that expression, and !Boolean(x) is equivalent to !x. See the documentation about falsy values.
@user4642212 you are right. Do not need use empty array because if no elements pass the test array filter method returns an empty array.
@Ravi K you are right. I just used it to make it readable. Check the code now.
|
1

You can use the Array.prototype.filter() method in order to remove the non falsy values from the array and calculate the length of the filtered array like below:

const userArray = ["school", "science", "", "", null, "bachelors", "final", undefined, null];
  
const filteredArray = userArray.filter(value => !value);
console.log(filteredArray.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.