Trying to replicate the Implicit Iterators in Python, using JavaScript my code doesn’t return “Dylan”, despite being a male.
Python:
names = [person.name for person in roster if person.male]
JavaScript Algorithm Test:
roster = {
person: [
{
name: "Katie",
male: false
},
{
name: "Dylan",
male: true
},
{
name: "Alex",
male: true
},
{
name: "John",
male: true
}
]
}
var names = []
var number = -1
for(var loop = 0; loop < roster.person.length; loop++) {
if(roster.person[loop].male == true) {
names[number++] = roster.person[loop].name
}
}
console.info(names)
>>> [code] Returns –> [“Alex”, “John”]
Why is this? My loop goes through all the values and my if then statement is valid.
That’s because you are trying to insert an element at position
-1of the array. See Increment and decrement operators.Either use
++numberinstead ofnumber++:Or initialize the variable
numberto0instead of-1, or instead of using a variable to hold the current index value, just use.push, which adds a new element to the array.Also, you don’t need to explicitly compare with
true, it suffices that the expression evaluates totrue: