1 of 34

Arrays & Objects

Nathaniel Foster

Associate Instructor

TURING SCHOOL OF SOFTWARE & DESIGN

2 of 34

Objects

3 of 34

Enumerables

Object.keys

let pizza = {

crust: 'thin',

sauce: 'tomato',

cheese: true,

toppings: ['pepperoni', 'pineapple', 'onions']

}

let keys = Object.keys(pizza);

console.log(keys);

keys.forEach( key => console.log( pizza[key] ) );

4 of 34

Enumerables

let cheesePizza = {

topping: 'cheese'

}

let pepperoniPizza = cheesePizza;

pepperoniPizza.topping = 'pepperoni';

console.log(cheesePizza)

Object.assign

5 of 34

Enumerables

let cheesePizza = {

topping: 'cheese'

}

let pepperoniPizza = Object.assign({}, cheesePizza);

pepperoniPizza.topping = 'pepperoni';

console.log(cheesePizza)

Object.assign

6 of 34

Enumerables

let pizza = {

crust: 'thin',

sauce: 'tomato',

cheese: true,

toppings: ['pepperoni', 'pineapple', 'onions']

}

let pizzaParty = [];

for (let i = 0; i < 100; i++) {

let duplicate = Object.assign({}, pizza);

duplicate.number = i;

pizzaParty.push(duplicate)

}

console.log(pizzaParty[50])

Object.assign

7 of 34

Enumerables

Exercise

// add 1000 pizzas to each party room in the pizzaParty

let pizza = {

crust: 'thin',

sauce: 'tomato',

cheese: true,

toppings: ['pepperoni', 'pineapple', 'onions']

}

let pizzaParty = {

rad: [],

awesome: [],

mega: [],

wow: []

}

8 of 34

Arrays

9 of 34

Enumerables

What is an array?

Arrays "are high-level, list-like objects" (from MDN).

So arrays are really just objects where the keys are ordered numbers...

const holiday = {

0: 'pumpkin',

1: 'candy',

2: 'costumes'

}

holiday[1] === 'candy'

Object.keys(holiday);

// [ '0', '1', '2' ]

const holiday = [

'pumpkin',

'candy',

'costumes'

]

holiday[1] === 'candy'

Object.keys(holiday);

// [ '0', '1', '2' ]

10 of 34

Enumerables

Except...

Arrays come with their own special prototypes. For example:

  • Looping methods:
    • forEach, map, filter, find, reduce

  • Methods to add/remove items:
    • push, pop, unshift, shift, splice...

  • Methods to get information from a specific array:
    • length, lastIndexOf, Array.isArray,

11 of 34

Enumerables

Exercise!

Get in groups and do the following:

12 of 34

Enumerables

Array.prototype.forEach

forEach is the simplest of these functions. It simply executes the callback function for each of the elements in the array. This function does not return anything.

13 of 34

Enumerables

Array.prototype.forEach

// array.forEach() does not return anything so using a return in the

// callback function is useless

const spookyThings = ['ghost', 'black cat', 'ghoul', 'bat'];

const verySpookyThings = spookyThings.forEach( (spookyThing) => {

return spookyThing.toUpperCase();

} );

console.log(verySpookyThings); // undefined

14 of 34

Enumerables

Array.prototype.forEach

// You can modify the original array, though by using the array argument

const spookyThings = ['ghost', 'black cat', 'ghoul', 'bat'];

spookyThings.forEach( (spookyThing, index, array) => {

array[index] = spookyThing.toUpperCase();

} );

console.log(spookyThings); // uppercase array

15 of 34

Enumerables

Array.prototype.forEach

// We can create our own forEach function with the following code

Array.prototype.myForEach = function (callbackFunction) {

for (let i = 0; i < this.length; i++) {

callbackFunction(this[i], i, this);

}

}

16 of 34

Enumerables

Array.prototype.map

map is the same as forEach except that each time the callback is executed, whatever is returned from the callback is added to a new array that map returns.

17 of 34

Enumerables

let spookyThings = ['ghost', 'black cat', 'ghoul', 'bat'];

let halloween = spookyThings.map((spookyThing, index, array) => {

return spookyThing;

});

console.log(spookyThings); // what logs here?

console.log(halloween); // what logs here?

console.log(spookyThings === halloween); // what logs here?

Array.prototype.map

18 of 34

Enumerables

let spookyThings = ['ghost', 'black cat', 'ghoul', 'bat'];

let halloween = spookyThings.map((spookyThing, index, array) => {

return spookyThing.toUpperCase();

});

console.log(spookyThings); // what logs here?

console.log(halloween); // what logs here?

Array.prototype.map

19 of 34

Enumerables

// We can create our own map function with the following code

Array.prototype.myMap = function (callbackFunction) {

var newArray = [];

for (let i = 0; i < this.length; i++) {

let newElement = callbackFunction(this[i], i, this);

newArray.push( newElement );

}

return newArray;

}

Array.prototype.map

20 of 34

Enumerables

What method should you use if you want a new array with the same number of elements as the original array?

What method should you us if you only want to modify the original array?

What are the differences between forEach and map?

When should map be used instead of forEach?

When should forEach be used instead of map?

forEach vs map?

21 of 34

Enumerables

Array.prototype.find

Find returns the first array element where the callback function returns true.

22 of 34

Enumerables

Array.prototype.find

let spookyThings = [

{ name: 'ghost', scariness: 95, type: 'paranormal' },

{ name: 'black cat', scariness: 20, type: 'animal' },

{ name: 'ghoul', scariness: 55, type: 'paranormal' },

{ name: 'bat', scariness: 35, type: 'animal' }

];

let casper = spookyThings.find( spookyThing => {

return spookyThing.name === 'ghost';

} );

console.log(casper);

23 of 34

Enumerables

Array.prototype.filter

Filter returns all array elements where the callback function returns true.

24 of 34

Enumerables

Array.prototype.filter

let spookyThings = [

{ name: 'ghost', scariness: 95, type: 'paranormal' },

{ name: 'black cat', scariness: 20, type: 'animal' },

{ name: 'ghoul', scariness: 55, type: 'paranormal' },

{ name: 'bat', scariness: 35, type: 'animal' }

];

let paranormalThings = spookyThings.filter( spookyThing => {

return spookyThing.type === 'paranormal';

});

console.log(paranormalThings);

25 of 34

Enumerables

Array.prototype.find

// We can create our own find function with the following code

Array.prototype.myFind = function (callbackFunction) {

for (let i = 0; i < this.length; i++) {

if (callbackFunction(this[i], i, this) === true) {

return this[i]

}

}

return undefined;

}

26 of 34

Enumerables

// We can create our own filter function with the following code

Array.prototype.myFilter = function (callbackFunction) {

var array = [];

for (let i = 0; i < this.length; i++) {

if (callbackFunction(this[i], i, this) === true) {

array.push(this[i]);

}

};

return array;

}

Array.prototype.filter

27 of 34

Enumerables

Array.prototype.reduce

Reduce is great at turning an array into one value. This value could be a number, string, object, or another array. To accomplish this, reduce takes in two parameters. The first is a callback, the second is an accumulator. The accumulator is modified in our callback and eventually is returned from our reduce function.

28 of 34

Enumerables

Array.prototype.reduce

let numbers = [ 1, 2, 3, 3, 5 ];

let sum = numbers.reduce( ( accumulator, number, index, array ) => {

accumulator += number;

return accumulator;

}, 0 );

console.log(sum);

29 of 34

Enumerables

Array.prototype.reduce exercise

let spookyThings = [

{ name: 'ghost', scariness: 95, type: 'paranormal' },

{ name: 'black cat', scariness: 20, type: 'animal' },

{ name: 'ghoul', scariness: 55, type: 'paranormal' },

{ name: 'bat', scariness: 35, type: 'animal' }

];

// get total of all spooky things scariness

let totalScariness = spookyThings.reduce( ( total, spookyThing ) => {

// ?

return total;

}, 0);

console.log(totalScariness); // 205

30 of 34

Enumerables

Array.prototype.reduce exercise

let spookyThings = [

{ name: 'ghost', scariness: 95, type: 'paranormal' },

{ name: 'blackcat', scariness: 20, type: 'animal' },

{ name: 'ghoul', scariness: 55, type: 'paranormal' },

{ name: 'bat', scariness: 35, type: 'animal' }

];

// create super thing by combining name and all scariness into one object

let superScary = spookyThings.reduce( ( superThing, spookyThing ) => {

// ?

return superThing;

}, { /* something can go here */ });

console.log(superScary);

31 of 34

Enumerables

Array.prototype.reduce

// We can create our own reduce function with the following code

Array.prototype.myReduce = function (callbackFunction, accumulator) {

for (let i = 0; i < this.length; i++) {

accumulator = callbackFunction(accumulator, this[i], i, this);

}

return accumulator;

}

32 of 34

Exercise

33 of 34

let halloweenCostumes =

[ 'Eleven', 'Harry Potter', 'Darth Vader', 'bride', 'zombie', 'Eleven', 'mermaid', 'vampire', 'Eleven', 'Darth Vader', 'zombie', 'Eleven', 'dinosaur' ];

// Reduce this array so it tallies the costumes seen during Trick or Treating:

{

'Eleven': 4,

'Harry Potter': 1,

'Darth Vader': 2,

'bride': 1,

'zombie': 2,

'mermaid': 1,

'vampire': 1,

'dinosaur': 1

}

Enumerables

Array.prototype.reduce

34 of 34

Enumerables

Object.keys & Array.prototype.reduce

let spookyThings = [

{ name: 'ghost', scariness: 95, type: 'paranormal' },

{ name: 'black cat', scariness: 20, type: 'animal' },

{ name: 'ghoul', scariness: 55, type: 'paranormal' },

{ name: 'bat', scariness: 35, type: 'animal' }

];

// Reduce this array so it is organized by type in an object as seen below.

{

paranormal: [

{ name: 'ghost', scariness: 95, type: 'paranormal' },

{ name: 'ghoul', scariness: 55, type: 'paranormal' },

],

animal: [

{ name: 'black cat', scariness: 20, type: 'animal' },

{ name: 'bat', scariness: 35, type: 'animal' }

]

}