Table of Contents
Let's take a look at a very common data type which consists of a collection of other data types called arrays. Using arrays, you can store numbers, strings, objects, even other arrays, inside a single variable.
Creation
When you want to handle a collection of the same data type, you'll want to create an array. Here's an example of how to create one.
JAVASCRIPTconst drinks = ["water", "juice", "milk", "soda"];
Just like that, you've created a new array with four elements in them, and initiated the value of drinks
with it. You can also create an array with a single element, like this:
JAVASCRIPTconst drinks = ["water"];
Elements are the individual items in the array.
Retrieval
Now that you've put data inside the array, how do you retrieve it? If you specify the index, you can get the value at that index back.
Because JavaScript is zero-based (it starts counting from 0
instead of 1
), water
is actually at position 0
in the array, not 1
.
So, if you wanted to get back the first element in the array, it would be like this:
JAVASCRIPTconsole.log(drinks[0]);
HTMLwater
You can take this a step further and iterate over the entire array using a for loop.
JAVASCRIPTconst drinks = ["water", "juice", "milk", "soda"];
for (let i = 0; i < drinks.length; i++) {
console.log(drinks[i]);
}
HTMLwater
juice
milk
soda
We are initializing the value of i
to be 0
, and then looping until that value is equal to the number of elements in the array, in this case, 4
.
As the value goes from 0
to 1
, to 2
, and then to 3
, the values at each of those indexes is being logged to our console.
Another way to do this is to use the forEach method and arrow functions.
JAVASCRIPTconst drinks = ["water", "juice", "milk", "soda"];
drinks.forEach((drink) => {
console.log(drink);
});
You can even do this in one line:
JAVASCRIPTconst drinks = ["water", "juice", "milk", "soda"];
drinks.forEach((drink) => console.log(drink));
Reassignment
After you have initialized an array, you can modify the values at an index pretty easily. Say you want to replace milk
with coffee
, it is as simple as this:
JAVASCRIPTconst drinks = ["water", "juice", "milk", "soda"];
drinks[2] = "coffee";
console.log(drinks);
JAVASCRIPT["water", "juice", "coffee", "soda"]
All you need to do is provide the index you want to reassign and then set it equal to your new value.
Sort
You can sort you array by calling the sort
method on it.
JAVASCRIPTconst drinks = ["water", "juice", "milk", "soda"];
const sortedDrinks = drinks.sort();
console.log(sortedDrinks);
JAVASCRIPT["juice", "milk", "soda", "water"]
In the case of strings, it will sort the items alphabetically. Here's how to sort an array of numbers numerically:
JAVASCRIPTconst numbers = [31, 99, 2, 6, 27, 64];
numbers.sort(function(a, b) {
return a - b;
});
HTML(6) [2, 6, 27, 31, 64, 99]
We can pass to sort
a compare function that takes two items, compares them, and then returns true
or false
to determine which element should be in front of the other. In our case, since we are working with numbers, we simply get the difference between the two values. A positive difference returns true
and a negative difference returns false
. This sorts the array of numbers as we want to.
Push
With push, you can easily add new items to the end of your array. Just call push
on your array with the new item you want to add. Here's an example:
JAVASCRIPTconst drinks = ["water", "juice", "milk", "soda"];
drinks.push("tea"); // add "tea" to the end of this array
console.log(drinks);
JAVASCRIPT["water", "juice", "milk", "soda", "tea"]
Pop
Pop is the opposite of push. Call pop
on your array to remove the last item in your array. Here's an example:
JAVASCRIPTconst drinks = ["water", "juice", "milk", "soda"];
drinks.pop(); // remove the last item in this array
console.log(drinks);
JAVASCRIPT["water", "juice", "milk"]
Shift
The shift
method removes the first element of an array and then returns that element to you. Here's an example:
JAVASCRIPTconst chocolates = ["Snickers", "Kit-Kat", "Twix"];
const snack = chocolates.shift();
console.log(snack);
console.log(chocolates);
JAVASCRIPTSnickers
["Kit-Kat", "Twix"]
Unshift
The unshift
method adds elements to the beginning of the array and returns the new array's length to you. Here's an example:
JAVASCRIPTconst chocolates = ["Snickers", "Kit-Kat", "Twix"];
const newLength = chocolates.unshift("Milky Way", "3 Musketeers");
console.log(newLength);
console.log(chocolates);
JAVASCRIPT5
["Milky Way", "3 Musketeers", "Snickers", "Kit-Kat", "Twix"]
Concat
You can create a new array by concatenating two existing arrays. All you need to do is call concat
on one array, with the second array being the parameter. Here's an example:
JAVASCRIPTconst healthyDrinks = ["water", "milk"];
const unhealthyDrinks = ["juice", "soda"];
const allDrinks = healthyDrinks.concat(unhealthyDrinks);
console.log(allDrinks);
JAVASCRIPT["water", "milk", "juice", "soda"]
Slice
Using slice
, you can return a brand new array containing elements from a slice of the original array. Simply provide the method with the starting and ending indexes and it will do the rest.
JAVASCRIPTconst colors = ["purple", "red", "white", "blue", "gold"];
const slice = colors.slice(1, 4);
console.log(slice);
JAVASCRIPT["red", "white", "blue"]
If you only provide one parameter, it will use that number as the starting point, and copy the rest of the array.
JAVASCRIPTconst colors = ["purple", "red", "white", "blue", "gold"];
const slice = colors.slice(3);
console.log(slice);
JAVASCRIPT["blue", "gold"]
Finally, if you provide a negative index, it will just start from the end and go backwards to reach the starting index. Here's an example:
JAVASCRIPTconst colors = ["purple", "red", "white", "blue", "gold"];
const slice = colors.slice(-3);
console.log(slice);
JAVASCRIPT["white", "blue", "gold"]
Splice
The splice
method accomplishes a similar task as slice
except that splice
returns the elements removed instead of the elements requested. splice
also changes the original array, whereas slice
creates an entirely new one.
JAVASCRIPTconst foods = ["burger", "pizza", "donut", "bread", "pasta"];
foods.splice(2);
console.log(foods);
JAVASCRIPT["burger", "pizza"]
If you provide a second parameter, you can specify the number of elements to remove from the array starting from that index.
JAVASCRIPTconst foods = ["burger", "pizza", "donut", "bread", "pasta"];
foods.splice(2, 1);
console.log(foods);
JAVASCRIPT["burger", "pizza", "bread", "pasta"]
In this case we are going to index 2
, which is donut
, then removing 1
element. Thus, the new food
array is every item except for donut
.
Split
The split
method is used when you want to take a string and chop it into an array every time a certain character is encountered in that string. For example, here is splitting on the comma character:
JAVASCRIPTconst string = "peanut,butter,jelly,time";
const array = string.split(",");
console.log(array);
HTML(4) ["peanut", "butter", "jelly", "time"]
The text has been split up by the character we passed in. The first item in the array is the first word, the second item is the second word, and so on.
Join
The join
method is the opposite of the split
method. It takes an array of strings and concatenates them while inserting a character in between all the array elements to return a new string.
JAVASCRIPTconst array = ["peanut", "butter", "jelly", "time"];
const string = array.join(",");
console.log(string);
HTMLpeanut,butter,jelly,time
indexOf
The indexOf
method returns to you the index in the array where the item you pass as a parameter is found. Simply put, pass along what you want to find and indexOf
will tell you where it's at. Let's see an example:
JAVASCRIPTconst array = ["Tilted Towers", "Pleasant Park", "Greasy Grove", "Fatal Fields"];
const index = array.indexOf("Greasy Grove");
console.log(index);
HTML2
In our example, we had an array of 4 elements, and we wanted to know what index Greasy Grove
was in. Upon calling indexOf
, the result was 2
. That makes sense when you remember that the first element in an array has an index of 0
and not 1
. That is why the third element in the array has an index of 2
.
lastIndexOf
As you might imagine, lastIndexOf
is very similar to indexOf
except instead of returning the first/lowest index the element appears in, it returns the last. Let's try using the method to search for an element found multiple times.
JAVASCRIPTconst array = ["Tilted Towers", "Pleasant Park", "Greasy Grove", "Fatal Fields", "Pleasant Park", "Loot Lake"];
const index = array.lastIndexOf("Pleasant Park");
console.log(index);
HTML4
The element we used lastIndexOf
with appears twice in our array, but since the method returns the last index, it returned 4
instead of 1
.
includes
The includes
method return a boolean indicating if the element you pass in as a parameter exists in the array. It will return true
if the element exists, or false
if it does not.
JAVASCRIPTconst array = ["Tilted Towers", "Pleasant Park", "Greasy Grove", "Fatal Fields", "Pleasant Park", "Loot Lake"];
const a = array.includes("Tilted Towers");
const b = array.includes("Retail Row");
console.log(a);
console.log(b);
HTMLtrue
false
find
The find
method is a pretty useful method that returns the first element that passes a test that you define. You define a test as a function that takes an element as a parameter and returns true
if the element passed the test or false
if the element failed the test. The first element to pass the test gets returned. Let's see an example:
JAVASCRIPTconst ages = [43, 24, 37, 28, 49, 68, 63, 21, 63, 79];
function canRetire(number) {
return number >= 65;
}
console.log(ages.find(canRetire));
HTML68
Since 68
was the first element in the array to pass the test, which was to be equal to or greater than 65
, that number was returned.
findIndex
The findIndex
method simply returns the index of the element you would have gotten if you used find
.
JAVASCRIPTconst ages = [43, 24, 37, 28, 49, 68, 63, 21, 63, 79];
function canRetire(number) {
return number >= 65;
}
console.log(ages.findIndex(canRetire));
HTML5
The sixth element with the index of 5
was returned since it was the first element to pass the test.
Reverse
You can reverse all the elements of an array by calling JavaScript's reverse
method on an array.
JAVASCRIPTconst cities = ["New York", "Boston", "Los Angeles", "Houston", "Miami", "Chicago"];
cities.reverse();
console.log(cities);
HTML(6) ["Chicago", "Miami", "Houston", "Los Angeles", "Boston", "New York"]
Every
The method every
can be used to ensure that every element in the array meets a certain criteria. You can define this criteria by passing in a function the returns a boolean representing whether or not that criteria was met. Here's an example:
JAVASCRIPTconst ages = [23, 52, 42, 32, 19];
function isAnAdult(age) {
return age >= 18;
}
console.log(ages.every(isAnAdult));
HTMLtrue
Since every number is equal to or greater than 18
, the every
method returned true
. Watch when a single value does not meet the criteria though:
JAVASCRIPTconst ages = [23, 52, 15, 32, 19];
function isAnAdult(age) {
return age >= 18;
}
console.log(ages.every(isAnAdult));
HTMLfalse
As you might expect, because a single number in the entire array did not meet the criteria of being greater than or equal to 18
, the every
method returned false
.
Some
The some
method is sort of like the inverse of the every
method. While every
requires that all elements meet the criteria, the some
method only requires a single element to meet the criteria. In other words, only some, even a single element, need to meet the criteria for the entire method to return true
.
JAVASCRIPTconst numbers = [64, 23, 86, 38, 47, 119];
function isTripleDigit(number) {
return number >= 100;
}
console.log(numbers.some(isTripleDigit));
HTMLtrue
Since we had a single element that was a triple-digit number, 119
, the method returned true
, but watch when we do not have a single element that meets the criteria:
JAVASCRIPTconst numbers = [64, 23, 86, 38, 47, 32];
function isTripleDigit(number) {
return number >= 100;
}
console.log(numbers.some(isTripleDigit));
HTMLfalse
No elements in our array was a triple-digit number so the some
method returned false
.
forEach
The forEach
method calls a function you provide on every element in your array, in the order they appear in the array. It automatically passes in the element and index for you. This is another way you can iterate across an entire array and do something with each element.
JAVASCRIPTconst greetings = ["hello", "hola", "ciao", "bonjour"];
function logGreeting(element, index) {
console.log(index, element);
}
greetings.forEach(logGreeting);
HTML0 "hello"
1 "hola"
2 "ciao"
3 "bonjour"
Map
The map
function creates a new array from an existing one after calling a function on every element. Consider this scenario:
JAVASCRIPTconst names = ["Bill", "Kelly", "John"];
const intros = names.map(function(name) {
return "My name is " + name;
});
console.log(intros);
JAVASCRIPT["My name is Bill", "My name is Kelly", "My name is John"]
It took every element from the names
array, pre-pended every string element with My name is
and the result was a new array with three brand-new strings.
This function does not alter the original array.
Filter
The filter
method is useful for, well, filtering out elements you don't want from an array to form a new one.
JAVASCRIPTconst numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const odd = numbers.filter(function(number) {
return number % 2 == 1;
});
console.log(odd);
JAVASCRIPT[1, 3, 5, 7]
Essentially, your filter function simply needs to return true
or false
. Only elements that cause the function to return true
end up moving on to the new array, and the rest are filtered out.
Reduce
The reduce
method goes over every element and collects some information about each element, and then finally returns the collective result.
A simple way to demonstrate reduce
is to use it to sum up all the numbers in an array.
JAVASCRIPTconst numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const total = numbers.reduce(function(total, number) {
return total + number;
});
console.log(total);
JAVASCRIPT36
Instead of adding the numbers together, you can do anything you'd like and reduce
will return the final result for you.
Resources
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor