I have an array and I want to return the maximum consecutive count of the items which are bigger than 60 from the array. Here, the expected output should be 3. My current implementation is like this:
let arr = ['80', '70', '11', '88', '90', '61'];
function processInput(arr) {
var total = 0;
for (let i = 0; i < arr.length; i ) {
if (arr[i] > 60) {
total ;
}
console.log(total);
break;
}
return total;
}
processInput(arr);
I'm not sure if I should use break
here or not. Thanks in advance.
CodePudding user response:
Presented below is one possible way to achieve the desired objective.
Code Snippet
const maxConsec = (arr = [], limit = 0) => {
// two variables: max-count, and count, both set to initial 0
let cMax = 0, c = 0;
// iterate thru the array
for (const elt of arr) {
// if elt is above "60" (ie, limit)
if (elt > limit) c ; // increment count
else c = 0; // else, reset count back to 0
// if current count greater than "max-count"
if (c > cMax) cMax = c; // store current count as max
}
// return max-count
return cMax;
};
let arr = ['80', '70', '11', '88', '90', '61'];
const limit = 60;
console.log(
'maximum consecutive array elements above', limit,
'are\n', maxConsec(arr, limit)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added to the snippet above.
CodePudding user response:
This should work
let arr = ['80', '70', '11', '88', '90', '61'];
function processInput(arr) {
let initialValue = 0;
const initialValuesArray = [];
arr.reduce((prev,current) => {
if(current > 60)
{
initialValue = 1;
initialValuesArray.push( initialValue)
}
else
{
initialValue = 0;
}
}, 0);
const maxValue = Math.max(...initialValuesArray)
return maxValue;
}
const result = processInput(arr);
console.log(result);