+ 1
Possible hide first two output value
hello guys i just want to ask if possible to hide the first two false output values before getting the true value Here's my code let people = [ {name:'john'}, {name:'smith'}, {name:'jerry'}, {name:'peter'}, {name:'justine'}, {name:'rain'} ]; for (let i = 0; i <= people.length; i++) { if(people[i].name === 'jerry'){ console.log('jerry'); } else { console.log('false'); } } This is the output: false, false, jerry, false, false, false But my desire output: jerry, false, false, false Thank you in advance!
1 Respuesta
+ 4
You can achieve it by using a helper variable:
let people = [ {name:'john'}, {name:'smith'}, {name:'jerry'}, {name:'peter'}, {name:'justine'}, {name:'rain'} ];
let isDesiredNameFound = false;
for (let i = 0; i < people.length; i++) {
if(people[i].name === 'jerry'){
console.log('jerry');
isDesiredNameFound = true;
} else if(isDesiredNameFound) {
console.log('false');
}
}
https://code.sololearn.com/WE7I4QlpFrHa/?ref=app
Notice that i changed the for loop from
i <= people.length;
to
i < people.length;
It will crash with both, the less than & the equal to.