menu-button

Arrays

Recap

In the slides above, we learnt the arrays allow us to represent a collection of values as a single value:

var myList = [2,6,5,3,10,-2];

We can inspect the value at a particular position in an array, and overwrite them. Remember that arrays are zero-indexed, meaning we start counting from 0 (e.g. the 1st element of the array is position 0, the 2nd is position 1, and so on)


console.log(myList[2]); // outputs 5
myList[3] = "R";
console.log(myList); // outputs [2,6,5,"R",10,-2]

Useful array functions

For the tasks below, there are a number of array functions which will help you. Suppose var x = ['a','b','c','d','e']:

  • x.push('f'): Adds an extra item to the end of your array.
  • x.concat(['f','g']): Appends ('concatenates') two arrays together, producing a new array. The array x will be unaffected.
  • x.join(", "): Joins the elements of an array into one string, separated by the provided separator. Here we'd obtain "a, b, c, d, e"
  • "1, 2, 3".split(", "): The opposite - splitting an string using the provided separator, to produce an array. Here we'd obtain [1, 2, 3]
  • x.length: This gives the number of elements in the array, here 5. Note that length is a property of the array and not a function, so use .length not .length().
  • x.indexOf('c'): Locates the position of an element in the array. This expressions will evaluate to 2 (i.e. the 3rd position).
  • You may also want to investigate pop and split.

Mini Task #1: Reading and updating elements in an array

Write code that does the following:

  1. Creates an array with items 2, 9, 8, 5 and assigns it to be a variable x.
  2. Modifies the 2nd item to 10.
  3. Outputs the 3rd item to the console.
  4. Outputs the length of the array to the console.
Reset to Original Code     Fullscreen

Mini Task #2: Using a for loop

Write a function sumArray which inputs an array, and outputs the sum of the items in the array. The last line of your code within the function should be return yourArray, which will cause your function to output this value.

Reset to Original Code     Fullscreen

Mini Task #3: More for loops

Write a function arrayEvenLengths which inputs an array of strings, and outputs a new array which tells you whether each string has an even number of letters. For example arrayEvenLengths(["One", "Two, "Four"]) would output [false, false, true]. The last line within your function should be return yourArray.

You could always avoid use of a for loop by using the map function, as described in the slides.

Reset to Original Code     Fullscreen

Mini Task #4: Multi-dimensional arrays

The variable board contains the current state of a Connect 4 board. Write some code...