This is taking me way longer than it should to work this out, can someone please help?
I was asked this in an interview yesterday and thought I’d get it down on paper so I can remember next time, well I can’t
The question was sum all even numbers in the array and also account for the null, I thought I could do this
arr = [2, 3, 4, 5, null, 6, 9]
arr.forEach(i => {
if (i % 2 === 0) {
i = i + i
}
console.log(i)
return i
})
Then put it into it’s own variable functional programming style, like:
arr = [2, 3, 4, 5, null, 6, 9]
conat result = arr.forEach(i => {
if (i % 2 === 0) {
i = i + i
}
console.log(i)
return i
})
console.log(result)
This has totally killed any confidence I had and I’m beginning to think my whole life is a lie
arr = [2, 3, 4, 5, null, 6, 9] //Declare variables with `var`, `let`, or `const`
arr.forEach(i => {
if (i % 2 === 0) {
i = i + i //this doubles i; it doesn't sum it with other values
//in the array
}
console.log(i) //unnecessary except for testing
return i //forEach just executes some code for each item in the array
//the returned value is lost
})
You want to use something like .reduce()
instead.
I actually realized that the "account for null
" in the question isn’t usually going to make a difference, as null
just coerces to 0
.
const arr = [1,2,null,3,4];
function addEven(arr) {
return arr.reduce((acc, cur) => cur % 2 === 0 ? acc + cur : acc, 0);
}
addEven(arr); // => 6
^ works just as well.
Edit: I also just realized you need to initialize these with 0
, otherwise the first value of the array is used (even if odd).
1 Like
Thanks @lionel-rowe, there was so much wrong with it, I really need to practice more
Thanks
@Oxyrus and @jlave did you have anything to add?