Working with Arrays

Let's look at the following Array methods: forEach, map, filter, and reduce.

const facultyMembers = [
  {
    email: "dtang@usc.edu",
    title: "Part-time Lecturer",
    unitsTeaching: 4,
  },
  {
    email: "dent@usc.edu",
    title: "Associate Professor",
    unitsTeaching: 12,
  },
  {
    email: "zune@usc.edu",
    title: "Senior Lecturer",
    unitsTeaching: 14,
  },
  {
    email: "nayeonki@usc.edu",
    title: "Senior Lecturer",
    unitsTeaching: 8,
  },
];

Extracting usernames with a loop

const usernames = [];

for (let i = 0; i < facultyMembers.length; i++) {
  const facultyMember = facultyMembers[i];
  const username = facultyMember.email.replace("@usc.edu", "");
  usernames.push(username);
}

Extracting usernames with forEach

facultyMembers.forEach((facultyMember, i) => {
  const username = facultyMember.email.replace("@usc.edu", "");
  usernames.push(username);
});

map

Create a new array where each number in the original array is multiplied by 10:

[1, 2, 3].map((number) => {
  return number * 10;
});

Extracting usernames with map:

// arrow function has a return statement
const usernames = facultyMembers.map((facultyMember) => {
  return facultyMember.email.replace("@usc.edu", "");
});

// OR

// arrow function does not have a return statement
const usernames = facultyMembers.map((facultyMember) =>
  facultyMember.email.replace("@usc.edu", "")
);

Exercise

// This function will randomly resolve with an "API response" containing
// user data or reject with an error object.
function makeApiRequest() {
  const randomNumber = Math.random() * 100;

  if (randomNumber > 50) {
    return Promise.resolve({
      data: {
        users: [
          {
            id: 0,
            attributes: {
              first: "David",
              last: "Tang",
            },
          },
          {
            id: 1,
            attributes: {
              first: "Josh",
              last: "Chen",
            },
          },
        ],
      },
    });
  }

  return Promise.reject({
    error: "Request timed out",
  });
}

function fetchUsers() {
  // your implementation
}

fetchUsers().then(
  (users) => {
    console.log(users);
    // [
    //   { id: 0, first: 'David', last: 'Tang' },
    //   { id: 1, first: 'Josh', last: 'Chen' }
    // ]
  },
  (error) => {
    console.error(error); // 'Request timed out'
  }
);

Solution

filter

Filter the array to only even numbers:

[1, 2, 3, 4, 5, 6].filter((number) => {
  const isEven = number % 2 === 0;
  return isEven;
});

Filter the array to only those with a title of "Senior Lecturer":

// arrow function has a return statement
const seniorLecturers = facultyMembers.filter((facultyMember) => {
  return facultyMember.title === "Senior Lecturer";
});

// OR

// arrow function does not have a return statement
const seniorLecturers = facultyMembers.filter(
  (facultyMember) => facultyMember.title === "Senior Lecturer"
);

If we were to write this using a for loop:

const seniorLecturers = [];

for (let i = 0; i < facultyMembers.length; i++) {
  if (facultyMembers[i].title === "Senior Lecturer") {
    seniorLecturers.push(facultyMembers[i]);
  }
}

console.log(seniorLecturers);

reduce

Sum up the array of numbers:

[1, 2, 3].reduce((accumulator, number) => {
  // accumulator is the running total
  console.log(accumulator, number);
  return accumulator + number;
}, 0);

Summing up the total number of units being taught:

const totalUnitsTaught = facultyMembers.reduce((sum, facultyMember) => {
  return sum + facultyMember.unitsTeaching;
}, 0);

If we were to write this using a for loop:

let totalUnitsTaught = 0;

for (let i = 0; i < facultyMembers.length; i++) {
  totalUnitsTaught = totalUnitsTaught + facultyMembers[i].unitsTeaching;
}

console.log(totalUnitsTaught);