U3LA2.4: Updating and Deleting from Arrays

How can I manage data in my array?

Teacher Notes && Overview

In this lesson, students will learn to update and delete items from an array as they create a bubble pop game. Depending on future projects, they may use this skill often, or it may be somewhat dormant until Unit 4 - both are okay, as it offers great exposure and rounds out their skills with arrays.

Objectives

Students will be able to:

  • Add items to an existing list

  • Delete items from an existing list

Suggested Duration

~1 Period (~45 minutes)

NYS Standards

9-12.CT.4 Implement a program using a combination of student-defined and third-party functions to organize the computation.

9-12.CT.7 Design or remix a program that utilizes a data structure to maintain changes to related pieces of data.

9-12.CT.8 Develop a program that effectively uses control structures in order to create a computer program for practical intent, personal expression, or to address a societal issue.

9-12.DL.1 Type proficiently on a keyboard.

9-12.DL.2 Communicate and work collaboratively with others using digital tools to support individual learning and contribute to the learning of others.

Vocabulary

  • .indexOf() - will return the index of a specific item in the array

  • .splice() - adds/removes elements from an array at a specific index value

  • .push() - adds a new element to the end of the array

Planning Notes && Materials

Planning NotesMaterials

Resources

Assessments

Formative:

Summative:

Do Now/Warm Up (~5 - 10 minutes)

Ensure students are working in an editor with Collide2D linked, or be prepared to ask them to link it later in the lesson.

Ask students to create an array that is prepopulated with at least 5 object literals that have information to draw a circle. They should at a minimum have the x, y, w, h information, and time permitting, have any colors they would like the circles to be.

Encourage students to use the for loops they have learned previously to do this, but if they are feeling stuck, they can do it manually.

Removing Items from an Array (~15 minutes)

If students have not already, ask them to use a loop to display the ellipses on their screen. If they are using examples from the previous lesson, they likely will do something like this:

let bubbleList = []

function setup() {
  createCanvas(400, 400);
  
  for(i=0; i < 6; i++){
    bubbleList[i] = {x:random(width), y:random(height), w:random(20, 25), h:random(20,25)}
  }
}

function draw() {
  background(220);
  
  for(i=0; i < bubbleList.length; i++){
    ellipse(bubbleList[i].x, bubbleList[i].y, bubbleList[i].w, bubbleList[i].h)
  }
}

This is perfectly acceptable, and if you feel this is enough for your students, they can get by doing this - forever! However, there is another method they can use to iterate through lists that already have values - it's called a forEach loop and is a method that works specifically on populated arrays.

The forEach is a method that takes in a callback function as a parameter and then performs that action on each item in a list. If you would like to use that method, it would look like this:

let bubbleList = []

function setup() {
  createCanvas(400, 400);
  
  for(i=0; i < 6; i++){
    bubbleList[i] = {x:random(width), y:random(height), w:random(20, 25), h:random(20,25)}
  }
}

function draw() {
  background(220);
  
  bubbleList.forEach(bubble =>{
    ellipse(bubble.x, bubble.y, bubble.w, bubble.h)
  })
}

Because it is an array method (a function for a specific type of thing), you must call theArray.forEach. Then, in the parenthesis where your parameters usually go, you first give a name to the iterable variable - the thing that will represent each item in the list - then use a callback function with the arrow notation to indicate what action should be taken for each iterable. For some students this makes more sense than traditional for loops, and for others it may be more confusing. There are not situations in the curriculum where they must use this method, but it is nice to have in their backpocket!

Moving along, we now have bubbles on our screen. Let's make them interactive - let's say we want to click on our bubbles, and have them disappear. There are a few ways we can do this: the most basic are to have them move off the screen by changing the x and y values, or to make the width and height so small they can't be seen. But there's a better way! We can remove them from the array entirely.

To do this, first make sure you have Collide2D linked in your program. Then, let's use our function mousePressed() to add interactivity - this is because we only want this to happen once, when we first click our mouse.

Like with displaying all of our circles, we will use another loop here to check if they are being clicked:

function mousePressed(){
  for(i=0; i < bubbleList.length; i++){
    if(collidePointEllipse(mouseX, mouseY, bubbleList[i].x, bubbleList[i].y, bubbleList[i].w, bubbleList[i].h)){
      console.log("clicked a bubble")
    }
  }

We now have a conditional inside of our loop that is checking to see if each bubble has been clicked, and only when they are clicked, it will display the string in the console. You could also adjust this statement to: console.log(bubbleList[i], "clicked a bubble") to also display the object literal with all the bubble's information, if you'd like distinction!

So now, our bubbles will all respond to being clicked, but they don't vanish yet. We still need to delete them from our list. To do that in JavaScript, we need to do two things:

  1. Identify the bubble's position in our list

  2. Delete the object literal at that position

  3. This will automatically condense our list so everything else fills into the position and proceeds as usual!

We will use two methods to do this - .indexOf() which will get us the index value of our element, and .splice() which will remove the element at that index value. Our code would then look like this:

function mousePressed(){
  for(i=0; i < bubbleList.length; i++){
    if(collidePointEllipse(mouseX, mouseY, bubbleList[i].x, bubbleList[i].y, bubbleList[i].w, bubbleList[i].h)){
      console.log("clicked a bubble")
      let theIndex = bubbleList.indexOf(bubbleList[i])
      bubbleList.splice(theIndex, 1) //At theIndex's position, remove 1 element
    }
  }

And if we wanted to use a forEach loop, it would look like:

function mousePressed(){
  bubbleList.forEach(bubble => {
    if(collidePointEllipse(mouseX, mouseY, bubble.x, bubble.y, bubble.w, bubble.h)){
      console.log("clicked a bubble")
      let theIndex = bubbleList.indexOf(bubbleList[i])
      bubbleList.splice(theIndex, 1) //At theIndex's position, remove 1 element
    }
  })
}

Now, if they click the bubbles, they should see them vanish as the object gets deleted from the list!

NB: This is a great time to discuss how they could turn this into a function that could be reused. For example, you could walk students through creating a function called deleteFromList() that would take in a list and item, find the index of a given item, and then splice it away. You could also turn the entire for loop into a function that could be used to iterate through a list and delete an item!

Adding Items to Your Array (~10 - 15 minutes)

If we are loving clicking, we may notice that eventually we are out of bubbles and need to get more. While we could click play, that would require the page to reload - what if we don't want to do that? Let's create a button that will make more bubbles for us!

First, let's get a rectangle in our draw function that will display on the screen and can serve as our button:

  rect(10, 30, 110, 50)
  text("MORE BUBBLES!", 15, 60)

Now, we are also going to use function mousePressed() for this - we will just add below the code we wrote to delete our bubbles. Since Collide2D is already linked, we just need to tell our code to add a bubble, which we do using the .push() method. This will add an element, taken as a parameter to the end of the list.

Our code would look like this:

function mousePressed(){
  //your chosen for loop to make bubbles erase would live here!
  
  if (collidePointRect(mouseX, mouseY, 10, 30, 110, 50)){
    bubbleList.push({x:random(width), y:random(height), w:random(20, 25), h:random(20,25)})
}
}

And tah-dah! Just like that, you are adding elements to an array. Cool, right?

Student Practice (~5 - 10 minutes)

Ask students to work in groups to determine how they could make a button that makes many bubbles appear at once, or that can erase bubbles near each other (that's a very spicy challenge).

Wrap-Up (~5 minutes)

In whatever way you prefer to collect work, ask students to respond to one more of the following questions:

  1. Explain the process of deleting items from an array.

  2. Why are for loops useful when working with arrays?

  3. How might you use these skills in past or future projects?

Last updated