8B Recap of Array Programming With Loops and Map, Reduce, Filter
8B Recap of Array Programming With Loops and Map, Reduce, Filter
Cosmin E. Oancea
[email protected]
November 2023
Today we also Interact via Socrative
Go to:
www.socrative.com
then click the Login button in the right-top corner and select
student login. Enter room number
SSL7ODIK
(a) about 5
(b) about 10
(c) about 15
(d) about 20
(e) about 25
Test
After each lecture, in my own time, I read the slides again and
type in the console the coding examples from the slides and try to
understand what each is doing, e.g., by inserting print-outs.
(Honest answer)
TRUE
FALSE
Today’s Lecture
new Array(nexp ): an expression that creates a new array of length (determined by the
evaluation of expression) nexp ; all its elements are uninitialized:
l e t a r r = new A r r a y ( 1 + 2 * 2 ) ;
co n s o l e . l o g ( a r r . l e n g t h ) ; / / p r i n t s : 5
co n s o l e . l o g ( a r r [ 0 ] ) ; / / p r i n t s : undefined
new Array(nexp ).fill(vexp ): an expression that creates a new array of length nexp with
all elements initialized to the value resulted from the evaluation of expression vexp :
l e t a r r = new A r r a y ( 2 + 3 ) . f i l l ( 3 * 1 1 ) ;
co n s o l e . l o g ( a r r , l e n g t h ) ; / / p r i n t s : 5
co n s o l e . l o g ( a r r ) ; / / p r i n t s : [ 3 3 ,3 3 ,3 3 ,3 3 ,3 3 ]
Let’s Recap: How Do We Read and/or Modify an Array?
exp arr[exp ind]: returns the element at position exp ind from the array exp arr
exp arr is an expression whose evaluation produces an array;
exp ind is an expression whose evaluation produces an integer.
l e t a r r s t r s = [ ” I ” , ” l o ve ” , ” prog ” + ” ramming ” , ” ! ” ] ;
co n s o l e . l o g ( a r r s t r s [ a r r s t r s . l e n g t h −2] ) ;
l e t p e n u l t i m a t e e l e m e n t = a r r s t r s [ a r r s t r s . l e n g t h −2];
co n s o l e . l o g ( p e n u l t i m a t e e l e m e n t ) ;
What does it print? Prints: ”programming” twice
exp arr.push(exp elm): adds a new element (resulted from evaluating expression
exp elm) to the end of array exp arr:
a r r s t r s . push ( ” F a l s e ! ” ) ;
co n s o l e . l o g ( a r r s t r s . l e n g t h ) ; / / p r i n t s : 5
co n s o l e . l o g ( a r r s t r s ) ;
What does it print? Prints: [”I”, ”love”, ”programming”, ”!”, ”False!”]
exp arr.pop(): removes the last element from the array (resulted from evaluating
the expression) exp arr and returns it:
l e t l a s t e l m = a r r s t r s . pop ( ) ;
co n s o l e . l o g ( a r r s t r s . l e n g t h ) ; / / p r i n t s : 4
co n s o l e . l o g ( l a s t e l m ) ; co n s o l e . l o g ( a r r s t r s ) ;
What does it print? Prints: ”False!”, then prints: [”I”, ”love”, ”programming”, ”!”]
Today’s Lecture
TRUE
FALSE
Creating a new Array
After executing statement:
l e t x = new A r r a y ( 10 * 10+1 ) ;
x will hold an array containing 101 elements that are all zero
TRUE
FALSE
Array Literals
After executing the statement:
variable x holds:
(a) the string "1234"
(b) the array whose elements are the strings "1", "2", "3" and "4"
(c) the integer value 1234
(d) the array whose elements are the integers 1, 2, 3 and 4
(e) an undefined value
Strings vs Arrays
What is printed after executing the small program below?
l e t x = ” TEXT ” ;
l e t y = [ ” T ” , ” E ” , ”X ” , ” T ” ] ;
x [ 2 ] = ”S ” ;
y [ 2] = ”S ” ;
co n s o l e . l o g ( x ) ;
co n s o l e . l o g ( y ) ;
(a) it prints "TEST" and then ["T", "E", "S", "T"], i.e., both are modified
(c) it prints "TEXT" and then ["T", "E", "X", "T"], i.e., none are modified
(d) it prints "TSXT" and then ["T", "E", "X", "T"], i.e., x is modified
(a) arr.push(el);
(b) el.push(arr);
(c) push.arr(el);
(d) el.pop(arr);
let x = [ ] ;
x . push ( 234 ) ;
x . push ( 1 ) ;
co n s o l e . l o g ( x [ x . l e n g t h −2 ] ) ;
TRUE
FALSE
Indexing
What does the following code prints?
l e t x = [ ” You ” , ” h a t ” + ” e ” , ” programming ” , ” ! ” ] ;
let a = x [1];
co n s o l e . l o g ( a [ 2 ] ) ;
(b) "u"
(d) "t"
* * * code f r a g m e n t * * *
}
return min el ;
}
f u n c t i o n s e t E ve r yE i g h t h E l e m e n t To 3 3 3 ( a r r ) {
}
Programming Arrays With Loops
The function below is supposed to receive as argument a
two-dimensional array of numbers (i.e., a matrix or a table) and to
return a new (one-dimensional) array whose elements are the
sum of each row in the table.
Please implement the body of the function:
f u n c t i o n sumUpMatRows ( t a b l e ) {
}
Summing Up Each Row of a Matrix/Table
Programming is the art of splitting a complex problem into
a number of smaller, manageable subproblems, then solving
each subproblem individually, and composing them back to
solve the complex problem.
f o r ( l e t i = 0 ; i < t a b l e . l e n g t h ; i = i + 1 ) { / / t r a v e r s e t h e r o ws
/ / g e t t h e c u r r e n t row
/ / compute i t s sum
return result ;
}
Summing Up Each Row of a Matrix/Table
Assume that we have already implemented a function named
sumVector that receives as argument a one-dimensional array
and returns the sum of its elements, e.g.,
console.log( sumVector( [1,2,3,4] ) );
will print 10 i.e., 1+2+3+4 = 10
How do we implement our main/complex function that produces
a table by summing up its rows?
f u n c t i o n sumUpMatRows ( t a b l e ) {
let result = [ ] ;
return result ;
}
Computing the Sum of the Elements of a Vector
Implement a function named sumVector that receives as
argument a one-dimensional array (i.e., a vector) and returns the
sum of its elements, e.g.,
f u n c t i o n sumUpVector ( v e c t o r ) {
/ / declare a va r i a b l e ‘ result ‘ & i n i t i a l i z e i t with ze r o
/ / add i t t o t h e ‘ result ‘
}
/ / r e t u r n the ‘ result ‘
}
Computing the Sum of the Elements of a Vector
Implement a function named sumVector that receives as
argument a one-dimensional array (i.e., a vector) and returns the
sum of its elements, e.g.,
f u n c t i o n sumUpVector ( v e c t o r ) {
let result = 0; / / d e c l a r e and i n i t i a l i z e t h e ‘ r e s u l t ‘ with 0
r e s u l t = r e s u l t + c u r r e n t e l e m ; / / add i t t o t h e r e s u l t
}
}
When should I use map or reduce or filter?
Use map when you want to
When should I use map or reduce or filter?
Use map when you want to
transform each element of an array into something else,
independently on each other.
e.g., multiply each element by 2, convert each string element
to a number, do something which each row of an table.
Use filter when you want to
When should I use map or reduce or filter?
Use map when you want to
transform each element of an array into something else,
independently on each other.
e.g., multiply each element by 2, convert each string element
to a number, do something which each row of an table.
Use filter when you want to
keep only the array elements that succeed under a predicate,
e.g., keep only the even elements from an array of integers,
keep only the strings that are palindromes, keep only the
elements that are greater than 7, keep only the rows of a
matrix whose sum is greater than 100.
Use reduce when:
When should I use map or reduce or filter?
Use map when you want to
transform each element of an array into something else,
independently on each other.
e.g., multiply each element by 2, convert each string element
to a number, do something which each row of an table.
Use filter when you want to
keep only the array elements that succeed under a predicate,
e.g., keep only the even elements from an array of integers,
keep only the strings that are palindromes, keep only the
elements that are greater than 7, keep only the rows of a
matrix whose sum is greater than 100.
Use reduce when:
you want to compute a result across the elements of an array
typically the result has one less dimensions than the input: a
vector is reduced to a number, a matrix is reduce to a vector.
it extends a binary function (that has two arguments) — such
as +, *, min, max — to operate across all elements of an array.
Syntax for map, reduce, filter
Map:
/ / some f u n c t i o n t h a t r e c e i v e s one a r g u m e n t
function f ( a ) { return ( a + 1 ) ; }
l e t a r r = [ . . . ] ; / / some a r r a y
/ / p r o d u c e s a new a r r a y by c a l l i n g f one e a ch e l e m e n t o f ‘ arr ‘
l e t n e w a r r = a r r . map ( f ) ;
Syntax for map, reduce, filter
Map:
/ / some f u n c t i o n t h a t r e c e i v e s one a r g u m e n t
function f ( a ) { return ( a + 1 ) ; }
l e t a r r = [ . . . ] ; / / some a r r a y
/ / p r o d u c e s a new a r r a y by c a l l i n g f one e a ch e l e m e n t o f ‘ arr ‘
l e t n e w a r r = a r r . map ( f ) ;
Filter:
/ / some f u n c t i o n t h a t r e c e i v e s one a r g u m e n t and r e t u r n s t r u e o r f a l s e
function p ( a ) { return ( a < 7) ; }
l e t a r r = [ . . . ] ; / / some a r r a y
/ / b u i l d s a new a r r a y by k e e p i n g o n l y t h e e l e m e n t s ‘ e l ‘
l e t n e w a r r = a r r . f i l t e r ( p ) ; / / s u ch a s ‘ p ( e l ) == t r u e ‘
Syntax for map, reduce, filter
Map:
/ / some f u n c t i o n t h a t r e c e i v e s one a r g u m e n t
function f ( a ) { return ( a + 1 ) ; }
l e t a r r = [ . . . ] ; / / some a r r a y
/ / p r o d u c e s a new a r r a y by c a l l i n g f one e a ch e l e m e n t o f ‘ arr ‘
l e t n e w a r r = a r r . map ( f ) ;
Filter:
/ / some f u n c t i o n t h a t r e c e i v e s one a r g u m e n t and r e t u r n s t r u e o r f a l s e
function p ( a ) { return ( a < 7) ; }
l e t a r r = [ . . . ] ; / / some a r r a y
/ / b u i l d s a new a r r a y by k e e p i n g o n l y t h e e l e m e n t s ‘ e l ‘
l e t n e w a r r = a r r . f i l t e r ( p ) ; / / s u ch a s ‘ p ( e l ) == t r u e ‘
Reduce:
/ / some f u n c t i o n t h a t r e c e i v e s two a r g u m e n t s
f u n c t i o n g ( a , b ) { r e t u r n ( a +b ) ; }
l e t a r r = [ . . . ] ; / / some a r r a y
l e t a0 = . . . ; / / some i n i t i a l v a l u e
/ / b u i l d s a new a r r a y by s u c c e s s i v e l y a p p l y i n g ‘ g ‘ t o ‘ a0 ‘ and
l e t n e w a r r = a r r . r e d u ce ( g , a0 ) ; / / t o e a ch e l e m e n t o f ‘ a r r ‘
Which one should I use
If I have an input array of strings and I would like to create one
big string by concatenating together all the string elements of the
array, which operation should I use on the input array?
(a) map
(b) filter
(c) reduce
(d) push
(e) multiplication
Which one should I use
If I have an input array of strings and I would like to create a new
array that contains only the elements that represent numbers,
which operation should I use on the input array?
(a) map
(b) filter
(c) reduce
(d) push
(a) map
(b) filter
(c) reduce
(d) push
(a) map
(b) filter
(c) reduce
(d) push
f u n c t i o n f ( a ) { r e t u r n ( a+ a ) ; }
let x = [1 , 2 , 3];
l e t y = map . f ( x ) ;
co n s o l e . l o g ( y ) ;
TRUE
FALSE
What is printed?
What does the following code print when executed in console?
function f ( a , b ) {
i f ( a >= b ) {
return a ;
} else {
return b ;
}
}
l e t x = [ 5 , 4 , 3 , 2 , 7 , 8 , 1 0 , 9999999 , 5 5 , 8 8 , 9 9 , 2 3 , 77 , 2 7 ] ;
l e t y = x . r e d u ce ( f , 0 ) ;
co n s o l e . l o g ( y ) ;
(a) 0
(b) 99
(c) 9999999
(d) 2
(e) ”I should understand first what function ‘f‘ computes and
then generalize its behavior to all elements of the array ‘x‘”
What is printed?
When applied to a string str, isNaN(str) returns false if str
is the string representation of a number and true otherwise.
f u n c t i o n f ( s t r ) { r e t u r n isNaN ( s t r ) ; }
l e t x = [ ” 5 ” , ” The ” , ” 55 ” , ” 77 ” , ” s ky ” , ” i s ” , ” 9999999 ” , ” b l u e ” , ” 27 ” ]
let y = x . f i l t e r ( f ) ;
co n s o l e . l o g ( y ) ;
TRUE
FALSE
Horizontal Nesting: String Processing Example
Problem: we want to process a string inp str that consists of words separated by
comma and/or spaces in the following way:
(1) replace the commas with empty spaces;
(2) split the string into an array of words using space (” ”) as separator
(3) removing the words that are empty strings or that represent numbers from the array
obtained at step (2)
(4) upper-casing all words of the array obtained at step (3) and adding an "|"
character at the end of each.
(5) concatenating back all words into a string that starts with "|".
function processString ( i n p s t r ) {
l e t s t e p 1 s t r = i n p s t r . replace ( / [ , ] / g , ” ” ) ; / / r e p l a ce s ’ , ’ with ’ ’
l e t s t e p 2 a r r = s t e p 1 s t r . s p l i t ( ” ” ) ; / / p r o d u c e s an a r r a y o f wo r d s
l e t step3 arr = step2 arr . ???
l e t step4 arr = step3 arr . ???
l e t step5 str = step4 arr . ???
return step5 str ;
}
Horizontal Nesting: String Processing Example
Problem: we want to process a string inp str that consists of words separated by
comma and/or spaces in the following way:
(1) replace the commas with empty spaces: this can be achieved with
(2) split the string into an array of words using space (” ”) as separator
(3) removing the words that are empty strings or that represent numbers from the array
obtained at step (2)
(4) upper-casing all words of the array obtained at step (3) and adding an "|"
character at the end of each.
(5) concatenating back all words into a string that starts with "|".
function processString ( i n p s t r ) {
l e t s t e p 1 s t r = i n p s t r . replace ( / [ , ] / g , ” ” ) ; / / r e p l a ce s ’ , ’ with ’ ’
l e t s t e p 2 a r r = s t e p 1 s t r . s p l i t ( ” ” ) ; / / p r o d u c e s an a r r a y o f wo r d s
l e t s t e p 3 a r r = s t e p 2 a r r . f i l t e r ( a => a ! = = ” ” && isNaN ( a ) ) ;
l e t s t e p 4 a r r = s t e p 3 a r r . map ( word => word . toUpperCase ( ) + ” | ” ) ;
l e t s t e p 5 s t r = s t e p 4 a r r . r e d u ce ( ( a , b ) => a +b , ” | ” ) ;
return step5 str ;
}
Find the Maximal Element of Each Row of A Matrix
Problem: we want to create a new vector by selecting the maximal element of each row of
an input matrix (table of numbers).
Implementation plan:
Find the Maximal Element of Each Row of A Matrix
Problem: we want to create a new vector by selecting the maximal element of each row of
an input matrix (table of numbers).
Implementation plan:
(1) at the matrix level: should I use a map on the matrix or a reduce, or a filter?
(2) at row level: should I use a map on each row, or should I reduce each row, or should
I filter each row?
(3) at the level of numbers: what should the function be?
Find the Maximal Element of Each Row of A Matrix
Problem: we want to create a new vector by selecting the maximal element of each row of
an input matrix (table of numbers).
Implementation plan:
(1) at the matrix level: should I use a map on the matrix or a reduce, or a filter?
(2) at row level: should I use a map on each row, or should I reduce each row, or should
I filter each row?
(3) at the level of numbers: what should the function be?
f u n c t i o n max ( ? ? ? ) { ? ? ? }
f u n c t i o n maxVectorElm ( v c t ) { ? ? ? }
f u n c t i o n maxElemOfEachRow ( mat ) { ? ? ? }
Find the Maximal Element of Each Row of A Matrix
Problem: we want to create a new vector by selecting the maximal element of each row of
an input matrix (table of numbers).
Implementation plan:
(1) write a function that returns the larger of its two arguments;
(2) write a function that selects the maximal element of a vector, by applying reduce
with the function defined in step (1) and -Infinity as initial value
(3) write a function that solves our problem by mapping the input matrix with the
function of step (2).
(4) Bonus: implement the target function in one line.
/ / co m p u t e s t h e maximal between two numbers ( t e s t i t )
f u n c t i o n max ( a , b ) { i f a > b then r e t u r n a ; e l s e r e t u r n b ; }
/ / co m p u t e s t h e maximal e l e m e n t o f a v e c t o r ( t e s t i t )
f u n c t i o n maxVectorElm ( v c t ) { r e t u r n v c t . r e d u ce ( max , − I n f i n i t y ) ; }
/ / co m p u t e s t h e maximal e l e m e n t f o r e a ch row o f a m a t r i x ( t e s t i t )
f u n c t i o n maxElemOfEachRow ( mat ) { r e t u r n mat . map ( maxVectorElm ) ; }
/ / co m p u t e s t h e maximal e l e m e n t o f a v e c t o r
f u n c t i o n maxVectorElm ( v c t ) { r e t u r n v c t . r e d u ce ( max , − I n f i n i t y ) ; }
/ / co m p u t e s t h e maximal e l e m e n t f o r e a ch row o f a m a t r i x
f u n c t i o n maxElemOfEachRow ( mat ) { r e t u r n mat . map ( maxVectorElm ) ; }
f u n c t i o n maxElemOfMatrix ( mat ) {
l e t m a x e l e m f o r e a ch r o w = maxElemOfEachRow ( mat ) ;
l e t max elem = ? ? ?
r e t u r n max elem ;
}
maxElemOfEachRow( [ [3,444,5], [333,6,7,8], [0,2,1,555] )
results in one-dimensional array (vector) [444, 333, 555]
How do I compute the maximal element of [444, 333, 555]?
Find the Maximal Element of a Matrix
Problem: we want to compute the maximal element of an input matrix (two-dimensional
array/table of numbers) — i.e., the maximal element across all rows.
/ / co m p u t e s t h e maximal e l e m e n t o f a v e c t o r
f u n c t i o n maxVectorElm ( v c t ) { r e t u r n v c t . r e d u ce ( max , − I n f i n i t y ) ; }
/ / co m p u t e s t h e maximal e l e m e n t f o r e a ch row o f a m a t r i x
f u n c t i o n maxElemOfEachRow ( mat ) { r e t u r n mat . map ( maxVectorElm ) ; }
f u n c t i o n maxElemOfMatrix ( mat ) {
l e t m a x e l e m f o r e a ch r o w = maxElemOfEachRow ( mat ) ;
l e t max elem = maxVectorElm ( m a x e l e m f o r e a ch r o w ) ;
r e t u r n max elem ;
}
maxElemOfEachRow( [ [3,444,5], [333,6,7,8], [0,2,1,555] )
results in one-dimensional array (vector) [444, 333, 555]
How do I compute the maximal element of [444, 333, 555]?