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 |