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
Finding quarter based on month index in JavaScript
We are required to write a JavaScript function that takes in the 1-based month index and return the quarter which the month falls in.
Understanding Quarters
A year is divided into four quarters, each containing three months:
- Q1: January, February, March (months 1-3)
- Q2: April, May, June (months 4-6)
- Q3: July, August, September (months 7-9)
- Q4: October, November, December (months 10-12)
Method 1: Using if-else Statements
const month = 7;
const findQuarter = (month = 1) => {
if (month <= 3) {
return 1;
} else if (month <= 6) {
return 2;
} else if (month <= 9) {
return 3;
} else if (month <= 12) {
return 4;
}
};
console.log("Month", month, "is in quarter:", findQuarter(month));
Month 7 is in quarter: 3
Method 2: Using Math.ceil Formula
A more concise approach uses mathematical calculation:
const findQuarterMath = (month) => {
return Math.ceil(month / 3);
};
// Test with different months
console.log("Month 1:", findQuarterMath(1)); // Q1
console.log("Month 4:", findQuarterMath(4)); // Q2
console.log("Month 7:", findQuarterMath(7)); // Q3
console.log("Month 10:", findQuarterMath(10)); // Q4
Month 1: 1 Month 4: 2 Month 7: 3 Month 10: 4
Method 3: Using Array Lookup
const findQuarterArray = (month) => {
const quarters = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4];
return quarters[month - 1];
};
console.log("Month 5:", findQuarterArray(5));
console.log("Month 11:", findQuarterArray(11));
Month 5: 2 Month 11: 4
Complete Example with Validation
const getQuarter = (month) => {
// Input validation
if (month < 1 || month > 12 || !Number.isInteger(month)) {
return "Invalid month. Please enter a number between 1-12.";
}
return Math.ceil(month / 3);
};
// Test cases
const testMonths = [1, 3, 6, 8, 12, 0, 13];
testMonths.forEach(month => {
console.log(`Month ${month}: ${getQuarter(month)}`);
});
Month 1: 1 Month 3: 1 Month 6: 2 Month 8: 3 Month 12: 4 Month 0: Invalid month. Please enter a number between 1-12. Month 13: Invalid month. Please enter a number between 1-12.
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| if-else | High | Good | Long |
| Math.ceil | Medium | Best | Short |
| Array lookup | Medium | Good | Medium |
Conclusion
The Math.ceil formula Math.ceil(month / 3) is the most efficient approach for finding quarters. It's concise and performs well for large datasets.
Advertisements
