Javascript Arrays

Javascript Arrays - Storing Data In Lists

In JavaScript Arrays are a way to store multiple values in one variable. They’re great for storing a list of items. Creating an array is similar to creating a variable except you assign it with square brackets with your list of items inside . Make sure to wrap string items in quotes "string".

Creating Arrays
var array_name = [1, 2, 3]; 
console.log(array_name);

// You can empty an array like this. Removes all existing values. 
array_name = [];
console.log(array_name);    

// Creates an empty array
var empty_array = []; 

// Array of fruits 
var fruits = ["banana", "apple", "orange", "grape"];
console.log(fruits);
  
// Arrays can span multiple lines
var cars = [
  "Ford",
  "Tesla",
  "Volvo"
];
console.log(cars);

/* You can also create an array this way with the new keyword. The method above is preferred as it’s easier to read and faster to execute. This is just to show you another way of doing things that you might see */
var travel = new Array("Vietnam", "Canada", "Thailand", "Japan");
console.log(travel);

Access The Elements Of An Array

You can access the values by referring to an index number in the array. Array indexes start with 0 so the first item will have an index of 0.

Accessing Array Elements
// Create 2 Arrays
var fruits = ["Banana", "Apple", "Orange", "Grape"];
var cars = ["Ford", "Tesla", "Volvo"];

// Stores the first element in the car array "Ford" in a variable.
var name = cars[0]; 
console.log(name); 

// Prints out Banana in the console.
console.log(fruits[0]);  

// Changing a value of an element in an array. 
// You CAN modify an array with bracket notation unlike variables.
fruits[0] = "Water Melon";
console.log(fruits[0]);
Accessing Elements Inside Javascript Array

Nested Arrays [Multi Dimensional Arrays]

A nested or multidemensional array is an array inside of an array or an array of arrays.

Nested Arrays
// Nested Array / Multi Dimensional Array - An array inside an array
var multiDimensional = [   
   ["Universe 1", 34823], ["Universe 2", 19282]   
];
console.table(multiDimensional);
 
// Flatten a multidimensional array into one array
console.table(multiDimensional.flat(Infinity));
 
// Select a single value within a multidimensional array
var universeCoordinate = multiDimensional[0][1];  
console.log(universeCoordinate);
JavaScript Multi dimensional Arrays

Array Methods

toString() Converts an array to a string with each value separated with a comma.
join() Joins an array into a string but allows you to specify your own separator.
pop() Removes the last value from an array. It can also return the last element in the array.
push() Adds a new element to the end of an array. It can also return the length of the new array.
shift() Removes the first element of the array. It can also return the value that was shifted out of the array.
unshift() Adds a new value to the beginning of an array.
splice() Add new elements to an array at a specified point.
concat() Creates a new array by joining 2 arrays together.
slice() Slices out a section of an array into a new array. It does not remove any values from the source array. Can take up to two arguments. A start and an end point.

Find a complete list of array methods here.

PUSH METHOD: Add items to the end of an array
// PUSH: Add items to the end of an array
var animals = ["cat", "dog", "tiger", "bird"];
animals.push("rabbit");

console.log(animals);
Push Method
UNSHIFT METHOD: Add items to the beginning of an array
// UNSHIFT: Add items to the beginning of an array
var animals = ["cat", "dog", "tiger", "bird"];
animals.unshift("rabbit");

console.log(animals);
POP METHOD: Removes the value from the end of the array. It can also return the last element in the array.
// POP: Remove an item from the end of an array
var animals = ["cat", "dog", "tiger", "bird", "rabbit"];
// Returns the last item in the array
removedAnimal = animals.pop();

console.log("Animal Array = " + animals);
console.log("Removed Animal = " + removedAnimal);
 Pop Method
TO STRING METHOD: Converts an array to a string with each value separated with a comma.
//TO STRING: Converts an array to a string with each value separated with a comma.
var services = ["Design", "Coding", "Web Development", "SEO"];
var servicesLine = services.toString();
console.log(servicesLine);
Javascript Arrays Tostring Method
JOIN METHOD: Joins an array into a string but allows you to specify your own separator. If omitted, the elements are separated with a comma.
//JOIN: Joins an array into a string but allows you to specify your own separator. 
var services = ["Design", "Coding", "Web Development", "SEO"];
var servicesLine = services.join(" | ");
console.log(servicesLine);
 Join Method
CONCAT METHOD: Creates a new array by joining 2 arrays together.
var fruits = ["Apple", "Orange"];
var vegetables = ["Carrot", "Spinach", "celery"];
var healthyFood = fruits.concat(vegetables);
console.log(healthyFood);
Concat Method
LENGTH METHOD: Get the length of an array
var greekSalid = ["Bell Pepper", "Cucumber", "Feta Cheese", "Dressing", "Red Onion", "Olives"];
var numberOfIngredients = greekSalid.length;
console.log(numberOfIngredients + "Ingredients of Greek Salad: " + greekSalid);
Javascript Arrays Length Method
SLICE METHOD: Slices out a section of an existing array then creates a new array from what's left over. It does not remove any values from the source array. Can take up to two arguments. A start and an end point.
var stocks = ["AXP - $85.05", "HOT.UN - $2.52", "BMO - $69.81", "BA - $128.56", "CPG - $1.48", "DFN - $4.79", "SPG - $57.17", "IVOV - $89.62"];

// Create a new array by taking out the first 5 and keeping the remainder
takeOutFirst5Stocks = stocks.slice(5);
console.log(stocks);  // Show original array is untouched
console.log(takeOutFirst5Stocks);
// New array starting at 2 & ends at 5. Resulting in 3 items from original 
console.log(stocks.slice(2,5));
// First 2 items
console.log(stocks.slice(0,2));
Javascript Arrays Slice Method
SPLICE METHOD: Adds / removes items from an array changing the existing array
// Adds / removes items from an array changing the existing array.
// (Parameter 1) Index position. Negative numbers start at the end.
// (Parameter 2) Number of items to remove.
// (Parameters 3+) Items to add

// Adds 2 items at index position 2
var activities = ["Yoga", "Working", "Sports", "Reading"];
activities.splice(2, 0, "Eating", "Dancing");
console.log(activities);

// At position 2, remove 2 items:
var activities = ["Yoga", "Working", "Sports", "Reading"];
activities.splice(2, 2);
console.log(activities);

Real World Example 

Grocery List Array
// Multi Dimensional Array
var groceryList = [    ["Tomato Soup: ", 3],   ["Green Tea: ", 2],   ["Chips: ", 1],   ["Carrot: ", 4]];

// POP: Removes the item from the end of the array
groceryList.pop();

//Adds a new item to the beginning of an array.
groceryList.unshift(["Eggs: ", 12]);

console.log(groceryList);
/* 
CONSOLE:
0: (2) ["Eggs: ", 12]
1: (2) ["Tomato Soup: ", 3]
2: (2) ["Green Tea: ", 2]
3: (2) ["Chips: ", 1]
*/

Facebook Video