Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Looping in JavaScript to count non-null and non-empty values
In JavaScript, counting non-null and non-empty values in an array is a common task. This article demonstrates how to use forEach() to iterate through an array and count valid values.
Basic Array Example
Let's start with an array containing subject names:
let subjectNames = ['JavaScript', 'Angular', 'AngularJS', 'Java'];
console.log("Original array:", subjectNames);
Original array: [ 'JavaScript', 'Angular', 'AngularJS', 'Java' ]
Using forEach() to Count Valid Values
The forEach() method executes a function for each array element. Here's the syntax:
yourArrayName.forEach(element => {
// Your logic here
});
Counting Non-Null and Non-Empty Values
To count valid values, we use a counter variable and check each element:
let subjectNames = ['JavaScript', 'Angular', 'AngularJS', 'Java'];
var count = 0;
subjectNames.forEach(subject => {
if(subject != '' && subject != null) {
count += 1;
}
});
console.log("Number of valid subjects: " + count);
Number of valid subjects: 4
Handling Mixed Data Types
Here's a more comprehensive example with null, empty, and undefined values:
let mixedData = ['JavaScript', '', null, 'Angular', undefined, 'Java', ' '];
var validCount = 0;
mixedData.forEach(item => {
if(item != null && item != undefined && item.trim() !== '') {
validCount += 1;
}
});
console.log("Mixed array:", mixedData);
console.log("Valid items count:", validCount);
Mixed array: [ 'JavaScript', '', null, 'Angular', undefined, 'Java', ' ' ] Valid items count: 3
Alternative Methods
You can also use the filter() method for a more concise approach:
let subjects = ['JavaScript', '', null, 'Angular', undefined, 'Java'];
// Using filter method
let validItems = subjects.filter(item => item != null && item != undefined && item !== '');
console.log("Valid count using filter:", validItems.length);
// Using reduce method
let countUsingReduce = subjects.reduce((count, item) => {
return (item != null && item != undefined && item !== '') ? count + 1 : count;
}, 0);
console.log("Valid count using reduce:", countUsingReduce);
Valid count using filter: 3 Valid count using reduce: 3
Comparison of Methods
| Method | Readability | Performance | Use Case |
|---|---|---|---|
forEach() |
Good | Good | When you need custom logic |
filter().length |
Excellent | Creates new array | Simple counting |
reduce() |
Good | Best | Complex calculations |
Conclusion
Use forEach() with conditional checks to count non-null and non-empty values. For simpler cases, consider filter().length for better readability.
Advertisements
