skip to Main Content

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


  1. it’s because you’re assigning at index i

    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]));
    

    or given this array

    evenNumbers[1] = 2
    evenNumbers[3] = 4
    evenNumbers[5] = 6
    

    with javascript filling up the empty space. you should use evenNumbers.push(arr[i]) instead

    Login or Signup to reply.
  2. It 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.

    function getEvenNumbers(arr) {
        const evenNumbers = [];
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] % 2 === 0) {
                evenNumbers.push(arr[i])
            }
        }
        return evenNumbers;
    }
    console.log(getEvenNumbers([1,2,3,4,5,6]));
    

    Even more, you can use Array.filter() function to do the same work.

    function getEvenNumbers(arr) {
        return arr.filter(n=>n%2===0);
    }
    console.log(getEvenNumbers([1,2,3,4,5,6]));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search