Arrays & Objects
Nathaniel Foster
Associate Instructor
TURING SCHOOL OF SOFTWARE & DESIGN
Objects
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] ) );
Enumerables
let cheesePizza = {
topping: 'cheese'
}
let pepperoniPizza = cheesePizza;
pepperoniPizza.topping = 'pepperoni';
console.log(cheesePizza)
Object.assign
Enumerables
let cheesePizza = {
topping: 'cheese'
}
let pepperoniPizza = Object.assign({}, cheesePizza);
pepperoniPizza.topping = 'pepperoni';
console.log(cheesePizza)
Object.assign
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
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: []
}
Arrays
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' ]
Enumerables
Except...
Arrays come with their own special prototypes. For example:
Enumerables
Exercise!
Get in groups and do the following:
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.
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
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
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);
}
}
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.
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
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
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
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?
Enumerables
Array.prototype.find
Find returns the first array element where the callback function returns true.
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);
Enumerables
Array.prototype.filter
Filter returns all array elements where the callback function returns true.
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);
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;
}
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
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.
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);
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
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);
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;
}
Exercise
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
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' }
]
}