code

JavaScript Arrays

// Assign values to array
var sandwich = ["peanut butter", "jelly", "bread"]

// Nest one Array within Another
var baseball = [["Bulls", 23], ["White Sox", 45]]

// Access Array Data with Indexes
var array = [50,60,70];
array[0];
var data = array[1];

// Modify Array Data With
var ourArray = [50,40,30];
ourArray[0] = 15;

// Access Multi-Dimensional Arrays With Indexes

var arr = [
  [1,2,3],
  [4,5,6],
  [7,8,9],
  [[10,11,12], 13, 14]
];
arr[3];
arr[3][0];
arr[3][0][1];

// Manipulate Arrays With push()

var arr1 = [1,2,3];
arr1.push(4);

var arr2 = ["Stimpson", "J", "cat"];
arr2.push(["happy", "joy"]);

// Manipulate Arrays With pop()Passed

var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown);
console.log(threeArr);

/* Manipulate Arrays With shift()
pop() always removes the last element of an array. What 
if you want to remove the first?

That's where .shift() comes in. It works just like .pop(), 
except it removes the first element instead of the last.
*/

var ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift();

/*
Manipulate Arrays With unshift()Passed

Not only can you shift elements off of the beginning 
of an array, you can also unshift elements to the 
beginning of an array i.e. add elements in front of the array.

.unshift() works exactly like .push(), but instead of adding 
the element at the end of the array, unshift() adds the element 
at the beginning of the array.

*/

// Nested Arrays

var ourArray = ["Stimpson", "J", "cat"];
ourArray.shift();
ourArray.unshift("Happy");

var ourPets = [
  {
    animalType: "cat",
    names: [
      "Meowzer",
      "Fluffy",
      "Kit-Cat"
    ]
  },
  {
    animalType: "dog",
    names: [
      "Spot",
      "Bowser",
      "Frankie"
    ]
  }
];
ourPets[0].names[1];
ourPets[1].names[0];

Leave a Reply

Matt is the author of five Apress books including Learn RStudio IDE, Quick, Effective, and Productive Data Science, Objective-C Recipes, Swift Quick Syntax Reference, Objective-C Quick Reference, and the upcoming Pro Data Visualization with R and JavaScript. He has over 20 years of experience in technology, psychometrics, and data analytics working in major higher education institutions such as The College Board and Educational Testing Service. He has earned a Master’s degree in Information Systems Management and a Bachelor’s degree in Quantitative Psychology.