To find the maximum number of 1s in a JavaScript array, we can interpret this question in two main ways:
🔹 Case 1: Count total number of 1s
Count all the
1s in the array (regardless of their position).
✅ Approach 1: Using filter()
const arr = [1, 0, 1, 1, 0, 1];
const count = arr.filter(x => x === 1).length;
console.log(count); // Output: 4
- ✅ Simple and readable.
- ❌ Creates a temporary array in memory.
✅ Approach 2: Using reduce()
const arr = [1, 0, 1, 1, 0, 1];
const count = arr.reduce((acc, curr) => acc + (curr === 1 ? 1 : 0), 0);
console.log(count); // Output: 4
- ✅ Memory efficient.
- ✅ Flexible for conditions.
✅ Approach 3: Using for loop
const arr = [1, 0, 1, 1, 0, 1];
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 1) count++;
}
console.log(count); // Output: 4
- ✅ Fastest.
- ✅ No extra memory.
- ✅ Good for large arrays.
🔹 Case 2: Find maximum number of consecutive 1s
Count the longest sequence of continuous 1s.
✅ Approach 1: Using for loop
const arr = [1, 1, 0, 1, 1, 1, 0, 1];
let max = 0, current = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 1) {
current++;
max = Math.max(max, current);
} else {
current = 0;
}
}
console.log("Max consecutive 1s:", max); // Output: 3
- ✅ Best approach for consecutive 1s.
- ✅ Handles mixed arrays easily.
🟢 Summary:
| Goal | Method | Description |
|---|---|---|
| Count total 1s | filter(), reduce(), or for loop |
Straightforward count |
| Max consecutive 1s | for loop with counters |
Track streaks of 1s |