Working with Arrays Flashcards

1
Q

What is an array?

A

Arrays are generally described as “list-like objects”; they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value.

“What is an array?” (MDN Web Docs). Retrieved November 7, 2023.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you create an array?

A

Arrays consist of square brackets and items that are separated by commas.

For example:

const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
const sequence = [1, 1, 2, 3, 5, 8, 13];
const random = ["tree", 795, [0, 1, 2]];

Note that we can also mix data types in a single array — we do not have to limit ourselves to storing the same type on all the items if the array

“Creating arrays” (MDN Web Docs). Retrieved November 7, 2023.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How can you find the length of an array?

A

By using the length property.

For example:

const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping.length); // 5
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can you access and modify array items?

A

Items in an array are numbered, starting from zero. This number is called the item’s index. So the first item has index 0, the second has index 1, and so on. You can access individual items in the array using bracket notation and supplying the item’s index, in the same way that you accessed the letters in a string.

Access example:

const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
console.log(shopping[0]);
// returns "bread"

Modifying example:

const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
shopping[0] = "tahini";
console.log(shopping);
// shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a multi-dimension array?

A

An array inside an array is called a multidimensional array.

Example:

const random = ["tree", 795, [0, 1, 2]];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you find the indexs of items in an array?

A

f you don’t know the index of an item, you can use the indexOf() method. The indexOf() method takes an item as an argument and will either return the item’s index or -1 if the item is not in the array:

const birds = ["Parrot", "Falcon", "Owl"];
console.log(birds.indexOf("Owl")); //  2
console.log(birds.indexOf("Rabbit")); // -1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How can you modify a multi-dimension array?

A

You can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this:

const random = ["tree", 795, [0, 1, 2]];
random[2][2]; // 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How can you add items to an array?

A

To add one or more items to the end of an array we can use push(). Note that you need to include one or more items that you want to add to the end of your array.

const cities = ["Manchester", "Liverpool"];
cities.push("Cardiff");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff" ]
cities.push("Bradford", "Brighton");
console.log(cities); // [ "Manchester", "Liverpool", "Cardiff", "Bradford", "Brighton" ]

To add an item to the start of the array, use unshift():

const cities = ["Manchester", "Liverpool"];
cities.unshift("Edinburgh");
console.log(cities); // [ "Edinburgh", "Manchester", "Liverpool" ]

“Adding items” (MDN Web Docs). Retrieved November 9, 2023.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can you remove items from an array?

A

To remove the last item from the array, use pop().

const cities = ["Manchester", "Liverpool"];
cities.pop();
console.log(cities); // [ "Manchester" ]

The pop() method returns the item that was removed.

To remove the first item from an array, use shift():

const cities = ["Manchester", "Liverpool"];
cities.shift();
console.log(cities); // [ "Liverpool" ]

If you know the index of an item, you can remove it from the array using splice():

const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
  cities.splice(index, 1);
}
console.log(cities); // [ "Manchester", "Edinburgh", "Carlisle" ]

In this call to splice(), the first argument says where to start removing items, and the second argument says how many items should be removed. So you can remove more than one item:

const cities = ["Manchester", "Liverpool", "Edinburgh", "Carlisle"];
const index = cities.indexOf("Liverpool");
if (index !== -1) {
  cities.splice(index, 2);
}
console.log(cities); // [ "Manchester", "Carlisle" ]

“Removing items” (MDN Web Docs). Retrieved November 9, 2023.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can you retrieve a sub array of items from an array?

A

With the slice() method. The slice() method of Array instances returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can you access every item from an array?

A

with the for...of statement:

const birds = ["Parrot", "Falcon", "Owl"];

for (const bird of birds) {
  console.log(bird);
}

or with the forEach Array method:

const array1 = ['a', 'b', 'c'];

array1.forEach((element) => console.log(element));

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

“Accessing every item” (MDN Web Docs). Retrieved November 9, 2023.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How can you do the same transformation to each item in an array?

A

With map() Array method. The code below takes an array of numbers and doubles each number:

function double(number) {
  return number * 2;
}
const numbers = [5, 2, 7, 6];
const doubled = numbers.map(double);
console.log(doubled); // [ 10, 4, 14, 12 ]

We give a function to the map() method, and map() calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array.

“Accessing every item” (MDN Web Docs). Retrieved November 10, 2023.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How filter the items on an array?

A

With filter() Array method. The code below takes an array of strings and returns an array containing just the strings that are greater than 8 characters long:

function isLong(city) {
  return city.length > 8;
}
const cities = ["London", "Liverpool", "Totnes", "Edinburgh"];
const longer = cities.filter(isLong);
console.log(longer); // [ "Liverpool", "Edinburgh" ]

Like map(), we give a function to the filter() method, and filter() calls this function for every item in the array, passing in the item. If the function returns true, then the item is added to a new array. Finally it returns the new array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How can you convert a string of comma separated values into an array?

A

With split() String method. In its simplest form, split() takes a single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array.

1.- Let’s play with this, to see how it works. First, create a string in your console:

const data = "Manchester,London,Liverpool,Birmingham,Leeds,Carlisle";

2.- Now let’s split it at each comma:

const cities = data.split(",");
cities;

3.- Finally, try finding the length of your new array, and retrieving some items from it:

cities.length;
cities[0]; // the first item in the array
cities[1]; // the second item in the array
cities[cities.length - 1]; // the last item in the array
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How can you convert an array into a string?

A

One way to do so is with the the join() method. Try the following:

const cities = [ "Manchester","London",Liverpool",Birmingham","Leeds","Carlisle" ];
const commaSeparated = cities.join(",");
commaSeparated; //  "Manchester,London,Liverpool,Birmingham,Leeds,Carlisle"

Another way to do so is to use the toString() method. toString() is arguably simpler than join() as it doesn’t take a parameter, but more limiting. With join() you can specify different separators, whereas toString() always uses a comma.

const dogNames = ["Rocket", "Flash", "Bella", "Slugger"];
dogNames.toString(); // Rocket,Flash,Bella,Slugger
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What makes array at() method useful?

A

The at() method is equivalent to the bracket notation when index is non-negative. For example, array[0] and array.at(0) both return the first item. However, when counting elements from the end of the array, you cannot use array[-1] like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading array["-1"], which is just a normal string property instead of an array index.

The usual practice is to access length and calculate the index from that — for example, array[array.length - 1]. The at() method allows relative indexing, so this can be shortened to array.at(-1).

By combining at() with with(), you can both read and write (respectively) an array using negative indices.

17
Q

How can you get the last index at which a given element can be found in the array?

A

With the lastIndexOf() method of Array instances returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

Syntax

lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)

Parameters

searchElement - Element to locate in the array.
fromIndex Optional - Zero-based index at which to start searching backwards, converted to an integer.

  • Negative index counts back from the end of the array — if fromIndex < 0, fromIndex + array.length is used.
  • If fromIndex < -array.length, the array is not searched and -1 is returned.
  • If fromIndex >= array.length or fromIndex is omitted, array.length - 1 is used, causing the entire array to be searched.

Return value

The last index of searchElement in the array; -1 if not found.