Why does an array of even numbers contain empty values?
function getEvenNumbers(arr) {
const evenNumbers = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
evenNumbers[i] = arr[i]
}
}
return evenNumbers;
}
console.log(getEvenNumbers([1, 2, 3, 4, 5, 6]));
console output: [empty, 2, empty, 4, empty, 6]
2
Answers
it’s because you’re assigning at index
i
or given this array
with javascript filling up the empty space. you should use
evenNumbers.push(arr[i])
insteadIt is because you are assigning a value to the i-th index of the array.
Since the odd value is skipped, they appear to be
empty
.You can push even numbers to the
evenNumbers
array.Even more, you can use
Array.filter()
function to do the same work.