H[oo|A]rray

 

Arrays in JavaScript....Hooray!

What Are Arrays?

  • Arrays are simply "lists of values"
  • Arrays CAN access values by their order or "index"
  • Arrays can NOT access values by name of elements
  • Arrays have a length....always
//This is an array of Strings
var myStringArray = ["I", "Am", "An", "Array"];

//This is an array of Numbers
var myNumberArray = [22, 45, 84, 1000, -1];

//This in an array of Objects
var myObjectArray = [{name: 'Jason'}, {name: 'Jon'}, {name: 'RayRay'}];

//This is an array of all the things
var allMyThingsArray = ["Who", 8, {name: 'Gilbert Grape'}];

Why Do We Use Arrays?

  • Arrays are an efficient and scalable way to pass logically grouped data throughout an application


     
  • They allow us to write applications that process collections of data of an undetermined or growing size
//We are sending all of our Reddit comments to a spam filter

var comment1 = "Dude you're stupid";
var comment2 = "No dude you're stupid";
var comment3 = "Actually, the meaning of the word stupid is deriven from the Latin dictionary...stupid people";
var comment4 = "I like cats."
var comment5 = "http://imgur.com/r/cats/3BisM9P";

//Call our function to send comments through spam filter
spamMeNot(comment1, comment2, comment3, comment4, comment5);

//Our spam filter in it's current state can take 5 comments
function spamMeNot(comment1, comment2, comment3, comment4, comment5){
    if(comment1 === spam){
        destroy();
    }

    if(comment2 === spam){
        destroy();
    }
    .
    .
    .
}

//What happens when we have another comment we need to process????

Imagine a world where...

//We are sending all of our Reddit comments to a spam filter

var comment1 = "Dude you're stupid";
var comment2 = "No dude you're stupid";
var comment3 = "Actually, the meaning of the word stupid is deriven from the Latin dictionary...stupid people";
var comment4 = "I like cats."
var comment5 = "http://imgur.com/r/cats/3BisM9P";

//Now we simply add all new comments to our array and don't have to change any other code
var myCommentArray = [];
myCommentArray.push(comment1);
myCommentArray.push(comment2);
myCommentArray.push(comment3);
myCommentArray.push(comment4);
myCommentArray.push(comment5);

//Call our function to send comments through spam filter
spamMeNot(myCommentArray);

//Our spam filter in it's current state can take 5 comments
function spamMeNot(comments){
    for(var i = 0; i < comments.length; i++){
        if(comments[i] === spam){
            destroy();
        }
    }
}

//What happens when we have another comment we need to process????

Arrays to the rescue!

Creating Arrays

There are "technically" 2 ways to create an Array

//Create a new Array
var myArray = [];
//Create an Array using the 'new' keyword
var someArray = new Array();
var someOtherArray = new Array(5);

The Right Way

The Wrong Way

What's the difference?

var myArray = [5];
=> [5]
myArray.length => 1

var myNewArray = new Array(5);
=> [undefined, undefined, undefined, undefined, undefined]
myNewArray.length => 5
  • Passing values to an Array literal constructor [] creates the Array with those values
  • Passing values(Number) to the new Array() constructor creates an array of that size.
  • [] - Array literal allocated memory for an Array
  • new Array() - calls the "constructor" of the Array object 

Accessing Arrays

We access "elements" of an array by their "index"

var myArray = ["Turkey", "Sandwiches", "Bacon", "Kitten"];
                  0            1          2        3

console.log(myArray.length) // 4

console.log(myArray[2]) // Bacon
console.log(myArray[4]) // undefined

//Assignment to existing Array
myArray[2] = "Donkey";

console.log(myArray); // ["Turkey", "Sandwiches", "Donkey", "Kitten"]

We call this "index notation"

Array Methods

For any existing array we have methods that we can call as a function of ANY array

  • pop
  • push
  • reverse
  • shift
  • sort
  • splice
  • unshift
  • concat
  • join
  • slice
  • indexOf
  • lastIndexOf
  • toString
  • toLocaleString

Reminder: Array methods have an action AND they return a result

Accessor Methods

Mutator Methods

Mutator Methods

These methods modify the Array

push()

Adds element(s) to the END of an Array

returns the new length of the Array

//Our initial array
var sports = ['soccer', 'baseball'];
console.log(sports.length) // 2

//PUSH new items to the end of the array, like pushing a new tennis ball into a jar
var lengthOfNewArray = sports.push('football', 'swimming');

console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(lengthOfNewArray);  // 4
console.log(sports.length); // 2

pop()

Removes the last element from the END of an Array

returns the VALUE removed from the Array

//Our initial array
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

console.log(myFish); // ['angel', 'clown', 'mandarin', 'sturgeon']
console.log(myFish.length) // 4

//Remove the LAST element from the array
var popped = myFish.pop();

console.log(myFish); // ['angel', 'clown', 'mandarin' ] 

console.log(popped); // 'sturgeon'

console.log(myFish.length) // 3

var doublePopped = myFish.pop();

console.log(myFish); // ['angel, 'clown'];

console.log(doublePopped); // 'mandarin'

console.log(myFish.length) //2

shift()

Removes the first element from the BEGINNING of an Array

returns the VALUE removed from the Array

//Our initial array
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

console.log(myFish.length); //4

var shifted = myFish.shift();

console.log(myFish); // ['clown', 'mandarin', 'surgeon']

console.log(shifted); // 'angel'

console.log(myFish.length); // 3

unshift()

Adds one or more elements to BEGINNING of array

returns the length of the new Array

//Our initial array
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

console.log(myFish.length); //4

var newLength = myFish.unshift('shark');

console.log(myFish); // ['shark', 'angel', 'clown', 'mandarin', 'surgeon']

console.log(newLength); // 5

console.log(myFish.length); // 5

//Can do multiple values
var newestLength = myFish.unshift('narwal', 'tako');

console.log(myFish); // ['narwal', 'tako', 'shark', 'angel', 'clown', 'mandarin', 'surgeon']

console.log(newestLength); // 7

console.log(myFish.length); // 7

reverse()

Reverses an array in exact opposite order

Returns the reversed array

var myArray = ['one', 'two', 'three'];
myArray.reverse(); 

console.log(myArray) // ['three', 'two', 'one']

sort()

Sorts the contents of an Array

no return value

//Initial array
var fruit = ['cherries', 'apples', 'bananas'];

fruit.sort(); 

console.log(fruit); // ['apples', 'bananas', 'cherries']

var scores = [1, 10, 2, 21]; 

scores.sort(); 

console.log(scores); // [1, 10, 2, 21]

var things = ['word', 'Word', '1 Word', '2 Words'];

things.sort(); 

console.log(things); // ['1 Word', '2 Words', 'Word', 'word']

Advanced: Compare Functions and Unicode

splice()

adds/removes items to/from an array

Note: This method changes the original array.

//Initial array
var fruits = ["Banana", "Orange", "Apple", "Mango"];

//Add items to the array:
fruits.splice(2, 0, "Lemon", "Kiwi");

console.log(fruit); // Banana,Orange,Lemon,Kiwi,Apple,Mango

Accessor Methods

These methods do NOT modify the original Array

They return a "representation" of the array

concat()

Takes a new array(s) and merges it with the calling array

Returns a new array of two array joined together

var alpha = ['a', 'b', 'c'];
var numeric = [1, 2, 3];

var alphaNumeric = alpha.concat(numeric);

console.log(alphaNumeric); // ['a', 'b', 'c', 1, 2, 3]

console.log(alpha); // ['a', 'b', 'c']

console.log(numeric); // [1, 2, 3]

The original (n) arrays remain unchanged

join()

Joins all elements of an array into a string

Returns a new String with all elements separated by "separator"

var a = ['Wind', 'Rain', 'Fire'];

var myVar1 = a.join();
console.log(myVar1); // 'Wind,Rain,Fire'

var myVar2 = a.join(', ');  
console.log(myVar2); // 'Wind, Rain, Fire' to myVar2

var myVar3 = a.join(' + '); 
console.log(myVar3); // 'Wind + Rain + Fire'

var myVar4 = a.join('');    
console.log(myVar4); // 'WindRainFire'

The original array remains unchanged

slice()

Copy a range of elements from an array

Returns a new Array with defined range of elements

// Our good friend the citrus from fruits example
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];

var citrus = fruits.slice(1, 3); 
//slice takes the start index and the index to stop at but NOT include in result

console.log(citrus); // ['Orange','Lemon']

console.log(fruits); // ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']

var noEndIndex = fruits.slice(1);

console.log(noEndIndex) // ['Orange', 'Lemon', 'Apple', 'Mango']

var negativeIndex = fruits.slice(2, -1);

console.log(negativeIndex); // ['Lemon', 'Apple']

The original array remains unchanged

If end is omitted, results default to end of Array

A negative end returns n indexes from the END of the Array

toString()

Copy a range of elements from an array

Returns a new String with all elements in Array

//Original Array
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr'];

//Converted to a string
var myVar = monthNames.toString();

console.log(myVar); // 'Jan,Feb,Mar,Apr'

The original array remains unchanged

indexOf()

Find the "index" of the element in an Array

Returns a Number of the "index" where element was found

var array = [2, 5, 9];

array.indexOf(2);     // 0

array.indexOf(7);     // -1 (Not Found)

array.indexOf(9, 2);  // 2

array.indexOf(2, -1); // -1

array.indexOf(2, -3); // 0

Optional: fromIndex to specify where to start search. A negative value will search from end of array.

lastIndexOf()

Find the "index" of the element in an Array

Returns a Number of the "index" where element was found

var array = [2, 5, 9, 2];

array.lastIndexOf(2);     // 3

array.lastIndexOf(7);     // -1

array.lastIndexOf(2, 3);  // 3

array.lastIndexOf(2, 2);  // 0

array.lastIndexOf(2, -2); // 0

array.lastIndexOf(2, -1); // 3

Optional: fromIndex to specify where to start search. A negative value will search from end of array.

H[ooA]rray

By Joe Karlsson

H[ooA]rray

Basic intro to Arrays in JavaScript.

  • 1,660