0% found this document useful (0 votes)
3 views

DevX JS - W6C15 - Array Methods.pptx

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DevX JS - W6C15 - Array Methods.pptx

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Javascript

Array Methods
Review
Review
● Loops: ● Git GUI
○ While Loops ○ Source Tree
○ Do-While ○ Commit
○ Loop Keywords ○ Compare
● Programming ○ Stash
○ What is good code?
Arrays in JS
var arr = []

Arrays in JS arr.push() // add an item to the end


arr.pop() // remove last item (and return it)
arr.shift() // remove first item (and return it)
Arrays in JS are useful. They can solve many arr.unshift() // add new first item

algorithmic problems.
arr.slice() // returns a subset of the array
arr.reverse() // flips the array
Arrays have MANY built-in methods.
arr.forEach() // does something to each item

You could program solutions to algorithmic arr.map() // makes a new array


arr.filter() // remove items from the array
problems by hand, but built-in methods are arr.reduce() // puts together the array into a single
usually better. value

Some problems cannot be easily solved by arr.splice() // adds items in a specific spot, removes
items
built-in methods. You should try to solve arr.sort() // orders the array
them by hand.
// THERE ARE MORE!!! THIS IS JUST SOME OF THEM!!!
Push and Pop
d var x = arr.pop();

a b c a b c
, , , , , ,

arr.push(“d”);
d
Unshift and Shift
! var x = arr.shift();

a b c b c
, , , , ,

arr.unshift("!");
a
Slice and Reverse
var x = arr.slice(1,3); var x = arr.reverse();

a b c d a b c d
, , , , , ,

b c d c b a
, , , ,
Array Methods
Array Methods
Solve each of these problems, starting with the array [1,2,3]. Console.log after each solution. Only
use array methods!

1. push 1. Add the number 4 to the end


2. unshift 2. Add the number 0 to the start var arr = [1,2,3]
3. pop 3. Remove the last item
// your code
4. shift 4. Remove the first item
5. slice 5. Log only [1,2] console.log(arr);
6. reverse 6. Log [3,2,1]
forEach()
forEach()
The next 4 methods use a processing function.

You pass a function parameter. The function takes an item from the array, and operates on it.

So in the function call, you must write a


function that takes an “item” from the arr.forEach(function (item) {
array, and does something.
console.log(item);
The term “item” in the code is a variable. if (item === "zintis") {
Any value can be assigned to it. console.log("teacher!");
}
Keep in mind that “forEach()” performs
the function FOR EACH item! }); the array item
(could be any name)
forEach()
arr.forEach(function (item) {
console.log(item); a b c
}); , ,

function item // ???

function item // ???

function item // ???


forEach(function)
You could also use a named function. These two are roughly equivalent:

arr.forEach(logOdds); arr.forEach(
function logEvenOdd(val) { function (val) {
if (val % 2) { if (val % 2) {
console.log("ODD!"); console.log("ODD!");
} else { } else {
console.log("EVEN!"); console.log("EVEN!");
} }
} });
forEach( )
forEach( )
● Instruction: This one should be quick. Just console.log each item in the array.

var arr = ['apple', 'banana', 'cherry', 'date', 'eggplant']

arr.forEach(function (item) {
// your code here
});
map()
map(function(){})
Map is similar to forEach(). It will RETURN a new array, which is modified according to the rules
in your function argument provides.

The difference here is that


forEach does NOT return a new var arr = [3,4,5]
array. map() creates a new array
of the values you returned.
var doubledArr = arr.map(function (item){
return item * 2;
});
console.log(doubledArr);
// 6, 8, 10
map() a
, b
, c

var x = arr.map(function (item) {


return item * 2;
});
function item // ???
console.log(x);

aa bb cc
, ,
map()
var arr = ["Alex Bacon", "Zintis May", "John Wick",

map() "Harrison Ford"];


var x = arr.map(function (item) {
var result;
These arrays have some information, // your code here
but not in the right format. return result;
});
Use map to fix them: console.log(x);

1. x should not have first names. It var arr2 = [ "Course: Arrays", "Course: While
should have “Mr.” instead. Loops", "Course: If/Else", "Course: Promises" ];
Eg: “Mr. Bacon” var y = arr2.map(function (item) {
2. y should read “Lesson:” instead of var result;
“Course:”. // your code here
Eg: “Course: Arrays” return result;
});
console.log(y);
filter()
filter()
Filter is similar to map(). But the function receives an array-item and returns true or false. If it
return true, it keeps the item. Returning false removes the item from the results.

So as the filter moves through the


array, if that particular item var arr = [3,4,5,6]
returns true, it is kept in the
result. If not, then removed.
var onlyOdds = arr.filter(function (item){
return item % 2 === 1;
In this example, x % 2 === 1 finds });
odd numbers. It returns either
console.log(onlyOdds);
true or false. 3 and 5 will be true,
so they are kept. // 3, 5
filter() a
, b
, c

var x = arr.filter(function (item) {


return item !== "a";
});
console.log(x);
function item // ???
a

b c
,
filter()
var arr = ["Alex Bacon", "Zintis May", "John Wick",

filter() "Harrison Ford"];


x = arr.filter(function (item) {
var result;
These arrays have some information, // your code here
but not in the right format. return result;
});
Use map to fix them: console.log(x);

1. x should contain no names with var arr2 = [ "Course: Arrays", "Course: While
the letter “a” in it! Loops", "Course: If/Else", "Course: Promises" ];
2. y should contain no lessons with y = arr2.filter(function (item) {
the letter “i” in it! var result;
// your code here
return result;
});
console.log(y);
reduce()
reduce()
This one is more complicated. Reduce takes two arguments. The point is to “reduce” the array
to a single value.

You start with the processing


function and a starting value. var arr = [1,2,3,4,5]

As you go through each


var total = arr.reduce(function (val,
array-item, you keep modifying item) {
the starting value. return val + item;
}, 0);
At the end, when all array-items
are processed, you return the console.log(total);
result. // 15
reduce()
var x = arr.reduce(function (agg, item) {
1 2 3 3
, , return agg + item;
}, 0);
console.log(x);

0
+item

function agg, item // ???

6
Understanding reduce()
Try running this code. Check the console. Read it carefully to understand how it works.

var arr = [1, 2, 3, 4, 5];


var total = arr.reduce(function (val, item) {
console.log(`Val is ${val}, item is ${item}, next val is ${val + item}`);
return val + item;
}, 0);
console.log(`Done, the total is: ${total}`);
Understanding reduce()
You can also use it in other ways. This code counts how many of each letter is in an array.

var arr = ["a", "a", "b", "a", "c", "c"];


var letterCounts = arr.reduce(function (val, item) {
if (val[item] > 0) {
val[item]++;
} else {
val[item] = 1;
}
return val;
}, {});
console.log(letterCounts);
Alternatives To reduce()
reduce() can be confusing to use at first.

Often you can use a simple for-loop, or a custom function instead.

Sometimes reduce is easier to work with, sometimes not.

function totalArrayValues(arr) {
var total = 0;
for (var item of arr) {
total += item;
}
return total;
}
splice()
splice(index, cut, insert)
splice() allows you to insert and remove sections of an array. It takes 2 or more arguments:
(1) Start of cut, (2) how many to cut, (3) what to insert.

splice() is flexible. It can remove


a segment without inserting var arr = ["a", "b", "x", "y", "z", "f"];
anything.
arr.splice(2, 3, "c", "d", "e");
The ‘insert’ argument lets you console.log(arr);
insert elements into the gap.

You can also remove zero items, var arr2 = ["a", "d"];
and insert items. Like in the arr2.splice(1, 0, "b", "c");
second example.
console.log(arr2);
splice()
In this example, splice() removes items starting
at the ‘1’ index. It removes 2 items.
arr.splice(1,2);
arr now had ONLY ‘a’ and ‘d’.

a b c d
, , ,

a d
,
splice()
In this example, splice() removes items starting
at the ‘1’ index. It removes 2 items.
arr.splice(3,0,’x’,‘y’);
It also inserts “x” and “y” at the same spot.

a b c d x y
, , ,
a b c x y d
, , , , ,
splice()
var x = arr.splice(1,2); var x = arr.reverse();

a b c d a b c d
, , , , , ,

a d d c b a
, , , ,
Splice
// remove 1

Splice var arr1 = [1, 2, 3, 3, 4, 5];


// insert 1
var arr2 = [1, 2, 4, 5];
Let’s fix these number lists.
//remove multiple
1. arr1 has an extra ‘3’, var arr3 = [1, 2, 3, 3, 3, 3, 4, 5];
remove it! //insert multiple
2. arr2 is missing a ‘3’, add it! var arr4 = [1, 2, 6, 7, 8];
3. arr3 has too many ‘3’s! // remove and insert
4. arr4 is missing ‘3,4,5’ var arr5 = [1, 2, 3, 4, 4, 4, 4, 8, 9, 10];
5. arr5 has too many ‘4’s
AND needs ‘5,6,7’ console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
console.log(arr5);
sort()
sort()
sort() is a generic algorithm that
orders items in an array. Given a var arr = [ 4, 2, 3, 1, 10 ]
comparison function, it can sort
however you want.
arr.sort()
console.log(arr)
As long as the comparison
function returns a negative,
var arr2= [ 40, 100, 1, 5, 25, 10 ];
positive, or zero, you can use
any logic to get there. arr2.sort( function (n1, n2) {
return n1 - n2;
sort() example here orders by
} );
alphabetically. The 2nd sorts
numerically. console.log(arr2)
sort()
sort() rearranges an array of values
in order. Without a processing var arr = ["Alex", "Zintis", "banana", "ants"];
function, it sorts alphabetically. arr.sort(function (w1, w2) {
var char1 = w1[0];
var char2 = w2[0];
Note: With no processing function, var isChar1Uppercase = (char1 === char1.toUpperCase ());
even an array of numbers is sorted var isChar2Uppercase = (char2 === char2.toUpperCase ());
alphabetically. if (isChar1Uppercase && !isChar2Uppercase ) {
return -1;
} else if (isChar2Uppercase && !isChar1Uppercase ) {
In this example we sort
return 1;
alphabetically and ALSO by } else {
uppercase/lowercase. return char1.charCodeAt (0) - char2.charCodeAt (0);
}
});
console.log(arr);
Sorting
var arr1 = ['z', 'c', 'x', 'b', 'y', 'a']

Sorting var arr2 = [456, 12, 98, 876, 1, 23, 345, 100]
var arr3 = ['Alex Bacon', 'Zintis May', 'Charles
Messini', 'Devin Soriano']
Sort each of these arrays. Post
var arr4 = [ 'lightning', 'fort', 'to', 'cat',
the screen shot of the console
'store', 'strong', 'a', 'markets', 'phonetic' ]
when done!

arr1.sort( // your code here )


1. Sort alphabetically
arr2.sort( // your code here )
2. Sort from smallest to
arr3.sort( // your code here )
largest
arr4.sort( // your code here )
3. Sort by last name,
alphabetically
console.log(arr1)
4. Sort from shortest to
longest word console.log(arr2)
console.log(arr3)
console.log(arr4)
Q&A

You might also like