I have tried so many time to solve this question but I couldn't accomplish the expected outcome. Here's the question in a nutshell:
Count all the values that are divisible by 11 in a given array
Return 0 if you encounter a number that is greater than or equal 111 regardless of the other divisible numbers of 11.
For example:
Input:
[11,12,22,33]Output:
3Input:
[11,12,22,33,136]Output:
0
I could solve the first part but failed with the second one.
Here is my code.
function div(list) {
let counter = 0
list.forEach((value) => {
if (value % 11 === 0) {
counter++
return counter
}
if(value>=111){
return 0
}
})
return counter
}
div([11, 22, 33, 44 , 116])
// OUTPUT : 4
Use a for loop instead so you can return inside if the break condition is found. Otherwise, return only at the end, not inside the loop.
function div(list) {
let counter = 0;
for (const value of list) {
if (value % 11 === 0) {
counter++
}
if (value >= 111) {
return 0
}
}
return counter
}
console.log(div([11, 22, 33, 44, 116]));
All the above answers works great, adding a different approach, letting the inbuilt method do the looping
function div(total, value) {
if (value % 11 === 0) {
total++;
}
if(value>=111){
total=0
}
return total;
}
console.log([11,12,22,33].reduce(div,0));
Use for...of loop to iterate over list and return inside loop when value is >= 111, otherwise keep counting the values divisible by 11.
function div(list) {
let count = 0;
for (const value of list) {
if(value >= 111){
return 0;
} else if (value % 11 === 0) {
count++;
}
}
return count;
}
console.log(div([11, 22, 33, 44 , 116]));