C4: Session 10

Arrays & Objects

Concept:
Arrays

Concept: Arrays

Creating an Array

An array in JavaScript is an ordered list of items. Using arrays, we can store several pieces of data in one variable.

Arrays are created using the square brackets [] and items in the arrays are comma-separated.  

const array = ['item1', 'item2', 'item3', ... , 'itemN'];

Concept: Arrays

Some examples:

const colors = ['red', 'blue', 'green', 'yellow', 'orange'];

const numbers = [1, 3, 4, 35, 7];

const ingredients = ['peanut butter', 'jelly'];

const emptyArray = [];

Concept: Arrays

Accessing items in an array

Each item in an array is assigned a position, known as the index. Arrays are zero-indexed which means that the first item in the array is positioned at index 0, the second at index 1, the third at index 2, and so on...

red blue green yellow orange
0 1 2 3 4
const colors = ['red', 'blue', 'green', 'yellow', 'orange'];

Concept: Arrays

Accessing items in an array

To access an element in an array, we use bracket notation. For example:

const colors = ['red', 'blue', 'green', 'yellow', 'orange'];

// To access "red"
colors[0];

// To access "blue"
colors[1];

// To access "green"
colors[2];

Concept: Arrays

Iterating over an array using a for loop

A common technique in JavaScript is to iterate through the contents of an array using for loops. 

const arr = ['item1', 'item2', 'item3', ... , 'item100'];

for (let i = 0;  i < arr.length; i++) {
  // outputs element at given index;
  console.log(arr[i]); 
}

Concept: Arrays

Example

// array containing prices of items in cart
const cartItems = [10, 20, 50, 5, 100];

// variable to track the running total
let total = 0;

// iterate over each item in cartItems and sum the prices
for (let i = 0; i < cartItems.length; i++) {
 total += cartItems[i];
}

// Print the result to console
console.log(total);

Concept: Arrays

Iterating over an array using a forEach loop

The forEach function is another method you can use to iterate over an array: 

const arr = ['item1', 'item2', 'item3', ... , 'item100'];

arr.forEach(callback);

The forEach method calls the callback function once for each element in the array, in ascending order, and passes the current element and index to the callback function.

Concept: Arrays

Example

// array containing numbers
const numbers = [1, 2, 3, 4, 5];

// iterate over each number and log out the message
numbers.forEach(function(number, index) {
  console.log(`Number ${number} is at index ${index} in the array`);
});

Concept: Arrays

Modifying the value of an item in an array

You can change the value of array items by accessing the item using bracket notation and reassigning a new value to the item.

const ingredients = ['bread', 'butter', 'jelly'];

// before
console.log(ingredients);

// modify butter to peanut butter
ingredients[1] = "peanut butter";

// after
console.log(ingredients);

Concept: Arrays

Adding to an array

You can append data to the end of an array using the push() function which takes one or more arguments and pushes them onto the end of the array. 

const cartItems = [10, 20, 50, 5, 100];

// before
console.log(cartItems);

// add two price items 
cartItems.push(99, 35);

// after
console.log(cartItems);

Concept: Arrays

Remove from an array

You can remove data from the end of an array using the pop() function. This function takes no arguments.

const cartItems = [10, 20, 50, 5, 100];

// before
console.log(cartItems);

// removes the last item
cartItems.pop();

// after
console.log(cartItems);

Concept: Arrays

Remove from an array

You can remove data at a specific index of an array using the splice() function. This function takes two arguments, the starting index to remove items and number of items to remove. 

const cartItems = [10, 20, 50, 5, 100];

// before
console.log(cartItems);

// remove 1 item starting at index 2
cartItems.splice(2, 1);

// after
console.log(cartItems);

Concept: Arrays

Finding the index of an item from an array

To find the index of an item, use the indexOf() function which takes in the value to search for as an argument. It returns the index of the first occurrence in the array. It returns -1 if the value is not found. 

const cartItems = [10, 20, 50, 5, 20, 100];

console.log(cartItems.indexOf(20)); // outputs 1

console.log(cartItems.indexOf(5)); // outputs 3

console.log(cartItems.indexOf(49)); // outputs -1

Concept Practice: Arrays

Random Restaurant Generator

  1. Create an array containing 5 different restaurant names.
  2. Write a function called getRandomRestaurant that takes in an array of restaurants and returns a random restaurant from the array.

Hints:

  • To calculate a random number in JavaScript, we can use
    • Math.floor(Math.random() * howManyNums)
      • Math.floor(num) rounds a number down to the nearest integer
      • Math.random() returns a random number between 0 (inclusive) and 1 (exclusive)

Concept Practice: Arrays

Random Restaurant Generator

// List of restaurants
const bbqRestaurants = [
  "Joe's KC", 
  "LC's BBQ",
  "Jack Stack",
  "Slaps",
  "Q39", 
];

function getRandomRestaurant(restaurants) {
  // Get a random number based on the number of restaurants in the array
  const randomIndex = Math.floor(Math.random() * restaurants.length);
  return restaurants[randomIndex];
}

let chosenRestaurant = getRandomRestaurant(bbqRestaurants)
console.log(chosenRestaurant);

Concept: Arrays

Nested Array

Arrays could be nested to create multi-dimensional arrays

const arr = [
  ['a', 'b'],
  ['d', 'e'],
  [
    ['111', '222', '333'], 
    ['444', '555', '666'], 
  ],
];

Concept: Arrays

Accessing items in nested arrays

When you use brackets to access your array, the first set of brackets refers to the items in the first layer of the array, and each additional pair of brackets refers to the next layer of items.

const arr = [
  ['a', 'b'],
  ['d', 'e'],
  [
    ['111', '222', '333'], 
    ['444', '555', '666'], 
  ],
];

const subArray = arr[2]; 
const nestedSubArray = arr[2][0]; 
const element = arr[2][0][1];

Concept Practice: Arrays

Random Restaurant Generator - Advanced

Given a list of restaurants and their distance from home, write a function called getRandomRestaurant that takes in an array of restaurants and a distance. Return a random restaurant from the array that is within the distance specified.

// List of restaurants
const bbqRestaurants = [
  ["Joe's KC",  5],
  ["LC's BBQ", 10],
  ["Jack Stack", 3],
  ["Slaps", 25],
  ["Q39", 9],
];

Concept Practice: Arrays

function getRandomRestaurant(restaurants, distance) {
  let isWithinDistance = false;
  let chosen = null;
  
  while (!isWithinDistance) {
    // Get a random number based on how many restaurants I have
    const randomIndex = Math.floor(Math.random() * restaurants.length);
    // check the distance
    if (restaurants[randomIndex][1] <= distance) {
      chosen = restaurants[randomIndex][0];
      isWithinDistance = true;
    }
  }
  
  return chosen;
}

let chosenRestaurant = getRandomRestaurant(bbqRestaurants, 17);
console.log(chosenRestaurant);

Concept:
Objects

Concept: Objects

Objects

An object is an unordered list of key-value pairs and each pair is called a property.

  • The key of a property must be a string
  • The value of a property can be any data type

Concept: Objects

Creating an Object

Objects are created using the curly braces {}. Properties in the object are comma-separated.

let personObj = {
  firstName: "John",
  lastName: "Smith",
  age: 30,
};

An object is an unordered list of key-value pairs and each pair is called a property.

Concept: Objects

Some Examples

const car = {
  brand: 'Tesla',
  model: 'X',
  year: 2023,
};

const productA = {
  sku: '012345',
  name: 'iPhone 14 Pro Max',
  screenSize: 6.7,
  colors: ['black', 'silver', 'purple'],
};

Concept: Objects

Accessing Items in the Object

There are two ways to access items in an object,

Concept: Objects

Accessing Items in the Object

There are two ways to access items in an object,

  • Dot Notation
let personObj = {
  firstName: "John",
  lastName: "Smith",
  age: 30,
};

// Get the firstName property
personObj.firstName;

// Get the age property
personObj.age;

Concept: Objects

Accessing Items in the Object

There are two ways to access items in an object,

  • Bracket Notation
let personObj = {
  firstName: "John",
  lastName: "Smith",
  age: 30,
};

// Get the firstName property
personObj['firstName'];

// Get the age property
personObj['age'];

Concept: Objects

Accessing Items in the Object

Bracket Notation

  • Useful when the keys are not in camelCase or snake_case
  • Note, the best practice is to use camelCase but sometimes you can't control the data that is returned to you.
let personObj = {
  "first-name": "John",
  "last-name": "Smith",
  age: 30,
};

// Get the firstName property
personObj['first-name'];

Concept: Objects

Accessing Items in the Object

You can also use a variable to access a property:

let personObj = {
  firstName: "John",
  lastName: "Smith",
  age: 30,
};

const keyToLookup = 'firstName';

personObj[keyToLookup];

Concept: Objects

Modifying Items

Similar to arrays, you can modify properties of an object by accessing the property by key and reassigning a value,

let personObj = {
  firstName: "John",
  lastName: "Smith",
  age: 30,
};

// before
console.log(personObj);

personObj.firstName = "Bob";

// after
console.log(personObj);

Concept: Objects

Adding Items

You can add new properties to existing objects the same way you would modify them:

let personObj = {
  firstName: "John",
  lastName: "Smith",
  age: 30,
};

// add the key "title" and assigns value to the key
personObj.title = 'Developer';

// after
console.log(personObj);

Concept: Objects

Removing Items

Use the delete keyword to remove items from an object:

let personObj = {
  firstName: "John",
  lastName: "Smith",
  age: 30,
  location: "New York",
};

delete personObj.location;

console.log(personObj);

Concept Practice: Objects

Profile Lookup

  1. Create a userProfile object that contains your firstName, lastName, and numberOfSiblings.
  2. Create a function getNumSiblings that takes in a profile object and returns the value of numberOfSiblings.

Concept Practice: Objects

Profile Lookup

const userProfile = {
  firstName: "Sharynne",
  lastName: "Azhar",
  numberOfSiblings: 2,
};

function getNumSiblings(profile) {
  return profile.numberOfSiblings;
}

const sibs = getNumSiblings(userProfile);
console.log(sibs); // returns 2

Concept: Objects

Nested Objects

Objects could be nested to create multi-leveled objects

const storage = {
  "desk": {
    "drawer": "stapler"
  },
  "cabinet": {
    "topDrawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottomDrawer": "soda"
  }
};

console.log(storage.cabinet.topDrawer); 

Concept: Objects

Mixing arrays and objects

Arrays of Objects

const players = [
  {
    name: "Mahomes",
    number: 15,
    position: "Quarterback",
  },
  {
    name: "Kelce",
    number: 87,
    position: "Tight End",
  },
  {
    name: "Edwards-Helaire",
    number: 25,
    position: "Running Back",
  }
];

console.log(players[0].name); // outpus "Mahomes"

Concept Practice: Objects

Profile Lookup - Advanced

  1. Create an array called userProfiles that contains a list of profile objects containing a user's firstName, lastName, and numberOfSiblings.
  2. Create a function getNumSiblings that takes in the parameters firstName and lastName, finds the correct profile based on the parameters, and returns the number of siblings.

Concept Practice: Objects

Profile Lookup - Advanced

// 1. Create an array called userProfiles that contains a list of profiles containing 
//    a user's firstName, lastName, and numberOfSiblings.
// 2. Create a function getNumSiblings that accepts firstName and lastName parameters 
//    and returns the number of siblings of the person that matches the given information.

const userProfiles = [
  { 
    firstName: "John",
    lastName: "Doe",
    numberOfSiblings: 1
  }, 
  { 
    firstName: "Bob",
    lastName: "Smith",
    numberOfSiblings: 10
  },
  { 
    firstName: "Jane",
    lastName: "Lee",
    numberOfSiblings: 2
  },
];

function getNumSiblings(firstName, lastName) {
  let foundProfile = null;
  
  // Iterate over each profile
  userProfiles.forEach(profile => {
    // If the first and last name matches 
    if (profile.firstName === firstName && profile.lastName === lastName) {
      foundProfile = profile.numberOfSiblings;
    }
  });
  
  // If not found, return message
  if (!foundProfile) {
    return "No matching profile";
  }
  
  return foundProfile;
}


// Call the function
let sibs = getNumSiblings('John', 'Doe');
console.log(sibs);

Extra Practice

JavaScript Practice

Next Session

The HTML DOM

C4-Session10

By Sharynne Azhar

C4-Session10

Arrays, Objects, and Functions

  • 15