CC-07: Array Iteration

with Carmen Salas • 2024/10/15

slides

Arrays

slides review...

for...of syntax when looping through an iterable's values:

for (let item of collection) {
    // iterating through values,
    // DOES NOT SKIP over undefined/skipped indices
}

for...in syntax when looping through an iterable's enumerables:

for (let index in collection) {
    // iterating through indices,
    // SKIPS over undefined/skipped indices
}

Code Challenge

  1. Declare a function named sumInArray that will calculate the sum of all the elements in an array of numbers. You must solve this without using any built-in array methods and iterating through the array.

const sumInArray = (arr) => {
  let sum = 0;
  for (let val of arr) {
    sum += val;
  }
  return sum;
}

// console.log(sumInArray([2,4,5,7,8])) // returns 26
// console.log(sumInArray([2,2,5,10])) // returns 19
// console.log(sumInArray([2,2,2,2,2])) //returns 10
  1. Declare a function named averageInArray that will calculate the average of the elements in an array of numbers. You must solve this without using any built-in array methods and iterating through the array.

const averageInArray = (arr) => {
  let sum = 0;
  for (let val of arr) {
    sum += val;
  }
  return sum / arr.length;
}

// console.log(averageInArray([2,4,5,7,8])) // returns 5.2
// console.log(averageInArray([2,2,5,10])) // returns 4.75
// console.log(averageInArray([2,2,2,2,2])) //returns 2

Last updated