Working with Arrays Flashcards
What is an array?
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.
How do you create an array?
Arrays consist of square brackets and items that are separated by commas.
For example:
javascript 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
How can you find the length of an array?
By using the length property.
For example:
const shopping = ["bread", "milk", "cheese", "hummus", "noodles"]; console.log(shopping.length); // 5
How can you access and modify array items?
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" ]
What is a multi-dimension array?
An array inside an array is called a multidimensional array.
Example:
const random = ["tree", 795, [0, 1, 2]];
How can you find the index’s of items in an array?
if 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 can you modify a multi-dimension array?
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 can you add items to an array?
How can you add items to an array?
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" ]
How can you remove items from an array?
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" ]
How can you retrieve a sub array of items from an array?
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 can you access every item from an array?
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”```
How can you do the same transformation to each item in an array?
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.
How filter the items on an array?
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 can you convert a string of comma separated values into an array?
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 can you convert an array into a string?
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 can you get the last index at which a given element can be found in the array?
To find the last index of a given element in an array, you can use the lastIndexOf
method in JavaScript or similar methods in other languages. Here are examples:
const array = [1, 2, 3, 2, 4]; const element = 2; const lastIndex = array.lastIndexOf(element); // Returns 3
What makes array at() method useful?
The at()
method in JavaScript, introduced in ECMAScript 2022, is useful for accessing array elements by index with several advantages:
-
Negative Index Support: Unlike traditional bracket notation (
array[index]
),at()
allows negative indices to access elements from the end of the array. For example,array.at(-1)
returns the last element, making it more intuitive thanarray[array.length - 1]
.javascript const array = [1, 2, 3, 4]; console.log(array.at(-1)); // 4 console.log(array.at(-2)); // 3
- Cleaner Syntax: It provides a concise and readable way to access elements, especially when working with dynamic or negative indices, avoiding cumbersome length calculations.
-
Works with Other Objects:
at()
is not limited to arrays; it works on any object with a length property and indexed elements, like strings or typed arrays.javascript const str = "hello"; console.log(str.at(-1)); // "o"
-
Chaining and Functional Programming: Since
at()
is a method, it can be chained in functional programming patterns or used in method chains, unlike bracket notation.const array = [1, 2, 3]; const result = array.map(x => x * 2).at(0); // 2
-
Safe and Explicit: It clearly indicates the intent to access an element at a specific index and returns
undefined
for out-of-bounds indices, consistent with other modern array methods.
In summary,at()
is useful for its flexibility with negative indices, readability, and compatibility with modern JavaScript practices, making it a valuable addition for array and string manipulation.