Search code examples
javascriptarraysfunctionhelper

Array Helpers javascript exercise


I am trying to solve an exercise about array helpers in Javascript, this is my code.

var numbers = [1, 2, 3, 4, 5];

function square() {
    var arraySquare = [];
    for (i = 0; i < numbers.length; i++) {
        arraySquare[i] = numbers[i] * numbers[i];
        arraySquare.push(arraySquare[i]);
    }
    return arraySquare;
}
console.log(square());

function cube() {
    var arrayCube = [];
    for (i = 0; i < numbers.length; i++) {
        arrayCube[i] = numbers[i] * numbers[i] * numbers[i];
        arrayCube.push(arrayCube[i]);
    }
    return arrayCube;
}
console.log(cube());

function arrayAverage() {
    var sum = 0;
    var average = 0;
    if (numbers === []) {
        return NaN;
    }
    else {
        for (i = 0; i < numbers.length; i++) {
            sum = sum + numbers[i];
        }
        average = sum / i;
    }
    return average;
}
console.log(arrayAverage());

function arraySum() {
    var sum = 0;
    for (i = 0; i < numbers.length; i++) {
        sum = sum + numbers[i];
    }
    return sum;
}
console.log(arraySum());

function even() {
   var arrayEven = [];    
   for (i = 0; i < numbers.length; i++) {
      if (numbers[i] % 2 === 0) {
          arrayEven.push(numbers[i]);
      } 
   }
   return arrayEven;
}
console.log(even());

function odd() {
    var arrayOdd = [];
    for (i = 0; i < numbers.length; i++) {
        if (numbers[i] % 2 !== 0) {
            arrayOdd.push(numbers[i]);
        }
    }
    return arrayOdd;
}
console.log(odd());

For some reason, the square() and cube() function, push the last element in the new arrays twice. Do you have any idea why this could happen? Aside from this, the code seems to work just fine. If you notice any other problem in the code please mention it!

Any help will be really appreciated!


Solution

  • Because you are setting the ith element, and after that you are pushing a new value onto the array:

    arrayCube[i] = numbers[i] * numbers[i] * numbers[i];
    arrayCube.push(arrayCube[i]);
    

    You should probably just do:

    arrayCube.push(numbers[i] * numbers[i] * numbers[i]);