Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

session-16 arrays #12

Merged
merged 23 commits into from
Mar 15, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added coursebook/session-16/JavaScript-while-loop.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions coursebook/session-16/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Arrays

### [**L**earning **O**utcomes](./learning-outcomes.md)
---
## **S**chedule

- 11:00 - 12:30 | [Arrays](./arrays.md)
- 12:30 - 12:45 | BREAK
- 12:45 - 14:00 | [Array Methods](./array-methods.md)

---
### [**A**dditional **R**esources](./resources.md)
Binary file added coursebook/session-16/array-methods.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
277 changes: 277 additions & 0 deletions coursebook/session-16/array-methods.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,277 @@

# Array Methods

**Author**: [@alaa-yasin](https://github.com/alaa-yasin) and [@Fatmasiam](https://github.com/Fatmasiam)


**Arrays have a good number of [methods](https://www.w3schools.com/jsref/jsref_obj_array.asp) such as _forEach()_, _map()_, _filter()_, _reduce()_, _sort()_, ..._etc_**

- What can you see after each method's name?
- What does that mean?
- What do you think the output will be if we don't write them?
```
[1,2,3].forEach; // ?
['Alaa', 'Islam', 'Aya'].map; //?
```
## So, what are methods?
**Methods are built-in or user-defined functions used in different cases.**

### - Built-in methods vs user-defined methods

* _Built-in method_ is any function that is provided by any language library. such as:
```js
[2, 3, 4].forEach();
[1, 2, true, "Ala'a"].map();
```
* Whereas, _user-defined methods are functions defined by users themselves in order to have their work done. such as:

```js
const array = [];
array.foo = function(num) {
return num * 3;
};
array.foo(3); //returns ??
```

**As we learned before, we can access arrays' elements by their index.**
```js
const numbers = [1, 2, 3];
numbers[0]; // 1
numbers[1]; //2
numbers[2]; //3
```

So, what if I have an array of 100 elements, and I want to _console.log_ everything in this array?
**Is it logical to access each element as this?**
```js
const cities = ['Gaza', 'Ramallah', ...etc]
cities[0];
cities[1];
...
...
...
cities[99];
```
## That is why methods are created :wink:
Fatmasiam marked this conversation as resolved.
Show resolved Hide resolved

1. ### **Array.forEach()**
```js
cities.forEach(function(city) {
console.log(city);
}); // Gaza, Ramallah ,...etc
```
So, [forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) is a function that executes a provided function once for each array element in ascending order.

**forEach()** method returns 'undefined'. It doesn't change the original array.

2. ### **Array.map()**

```js
const cities = ['gaza', 'ramallah']
cities.map(function(city) {
return city[0].toUpperCase() + city.slice(1);
}); // ['Gaza', 'Ramallah']
```

So. [map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) is a function that creates a new array populated with the results of executing a provided function on every array element.
**map()** method returns a new array with the same number of the original array elements. It doesn't change the original array.

3. ### **Array.filter()**
```js
const ages = [15, 34, 54, 46, 10, 4, 5];
ages.filter(function(age) {
return age < 18;
}); // [15, 10, 4, 5]
```
So, [filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) is a function that creates a new array with all elements that pass the test implemented by the provided function.
**filter()** method returns a new array with a different number of the original array elements. It doesn't change the original array.

4. ### **Array.reduce()**
hshahwan marked this conversation as resolved.
Show resolved Hide resolved
```js
const numbers = [1,2,3,4];
const initialValue = 0;
numbers.reduce(function(accumulator,currentValue) {
return accumulator + currentValue;
}, initialValue); // 10
```
### Let's split it:
```js
The first iteration:
accumulator = initialValue = 0
currentValue = first element = 1
first iteration output = 0 + 1 = 1
```
```js
The second iteration:
accumulator = first iteration output = 1
currentValue = second element = 2
second iteration output = 1 + 2 = 3
```
```js
The third iteration:
accumulator = second iteration output = 3
currentValue = third element = 3
third iteration output = 3 + 3 = 6
```
```js
The last iteration:
accumulator = third iteration output = 6
currentValue = last element = 4
last iteration output = 6 + 4 = 10
```
```js
So, The output value = 10
```
So, [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) is a function that executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
**reduce()** method returns a single output value. It doesn't change the original array.

5. ### **Array.sort()**
#### To sort strings:
```js
const letters = ['a', 'c', 'd', 'b', 'e', 'f'];

letters.sort(); // ["a", "b", "c", "d", "e", "f"]
```
#### To sort numbers in ascending order:
```js
const numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
}); // [1, 2, 3, 4, 5]
```
#### To sort numbers in descending order:
```js
const numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return b - a;
}); // [5, 4, 3, 2, 1]
```
So, [sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) is a function that sorts array elements in place and returns the sorted array.
**sort()** method returns a sorted array. It doesn't return a new array; it changes the positions of the elements in the original array.

6. ### **split and join**
Here’s the situation from real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: John, Pete, Mary. But for us an array of names would be much more comfortable than a single string. How to get it?

* The **str.split(delim)** method does exactly that. It splits the string into an array by the given delimiter delim.

In the example below, we split by a comma followed by space:
```js
let names = 'Bilbo, Gandalf, Nazgul';

let arr = names.split(', ');

for (let name of arr) {
console.log( `A message to ${name}.` ); // A message to Bilbo (and other names)
}

```

The `split` method has an optional second numeric argument – a limit on the array length. If it is provided, then the extra elements are ignored. In practice it is rarely used though:

```js
let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2);

console.log(arr); // Bilbo, Gandalf
```

**Split into letters**
```js
let str = "test";

console.log( str.split('') ); // t,e,s,t
```
The [split()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) method turns a String into an array of strings, by separating the string at each instance of a specified separator string.


**The call _arr.join(glue)_ does the reverse to split. It creates a string of arr items joined by glue between them.**

For instance:

```js
let arr = ['Bilbo', 'Gandalf', 'Nazgul'];

let str = arr.join(';'); // glue the array into a string using ;

console.log( str ); // Bilbo;Gandalf;Nazgul
```

The [join()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.


7. ### **pop/push, shift/unshift**
* [**push()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) method adds one or more elements to the end of an array and returns the new length of the array.
* [**pop()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) method removes the last element from an array and returns that element. This method changes the length of the array.
* [**unshift()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) method adds one or more elements to the beginning of an array and returns the new length of the array.
* [**shift()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) method removes the first element from an array and returns that removed element. This method changes the length of the array.


### Array: Push() :
**The push() method can append one or more elements to the end of an array.**
For example:

```js
let names = ['Fatma', 'Sama'];
names.push('Salwa');

console.log(names); // ['Fatma', 'Sama', 'Salwa']
// Push data onto the array. Push() appends elements to the end
// of the given array. Note that it can take more than one
// argument, each of which is individually appended to the array.
// In the output, notice that when push() takes multiple arguments
// they are appended in a left-to-right order (mimicing their
// appearence in the arguments list).
let letters = ['A', 'B'];
letters.push('C', 'D');

console.log(letters); // ['A', 'B', 'C', 'D'];
```

### Array: Pop()
**The pop() method pulls the last element off of the given array and returns it**
For example:

```js
let letters = [ 'A', 'B', 'C' ];

// Pop the element off of the end of the array.
console.log( letters.pop() ); // C
console.log( letters ); // ['A', 'B']
```

### Array: Unshift()
**The unshift() method is like the push() method, only it works at the beginning of the array. The unshift() method can prepend one or more elements to the beginning of an array.**

For example:

```js
let colors = [ 'red' ];

// Unshift data onto the array. Unshift() prepends elements to
// the beginning of the given array. Note that it can take more
// than one argument. In the output, notice that when unshift()
// takes multiple arguments, they are prepended in a right-to-left
// order (mimicing their appearence in the arguments list).
colors.unshift( 'yellow' );
colors.unshift( 'green', 'blue' );

// Output resultant array.
console.log( colors ); // ["green", "blue", "yellow", "red"]

```

### Array: Shift()
**The shift() method is like the pop() method, only it works at the beginning of the array. The shift() method pulls the first element off of the given array and returns it.**

For example:

```js
var numbers = [ 1, 2, 3 ];

// Shift the element off of the beginning of the array.
console.log( numbers.shift() ); //1
console.log( numbers ); // [2, 3]
```



![array-methods](./array-methods.jpg)
141 changes: 141 additions & 0 deletions coursebook/session-16/arrays.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
## Arrays

**Author**: [@Fatmasiam](https://github.com/Fatmasiam)

---

- [Arrays](#arrays)
- [Array Declaration](#array-declaration)
- [Manipulate Arrays](#manipulate-array)
- [Loops](./loops.md)

## <a href='#arrays' id='arrays'>Arrays : </a>
### **Onedimensional Arrays**: :arrow_double_down:
Objects allow you to store keyed collections of values. That’s fine.

But quite often we find that we need an ordered collection, where we have a 1st, a 2nd, a 3rd element and so on.
For example, we need that to store a list of something: users, goods, HTML elements etc.

It is not convenient to use an object here, because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use.

There exists a special data structure named Array, to store ordered collections.

#### What is **ARRAYS** means :
**Arrays** : Are single variables used to store ordered and different kind of elements(collections).

_SO_ : the array variable can hold more than one value at a time.



## <a href='#array-declaration' id='array-declaration'>Array Declaration : </a>
We have two ways to create(declare) empty array
```js
1- let arr = new Array();
// return arr = []
2- let arr = [];
Fatmasiam marked this conversation as resolved.
Show resolved Hide resolved
```
Almost all the time, the second syntax is used. and **W**e can supply initial elements in the brackets:

```js

let numbers = new Array(1, 2, 3);
console.log(numbers); // [1, 2, 3]

let colors = ['red', 'yellow', 'green', 'blue'];
console.log(colors); // ['red', 'yellow', 'green', 'blue']
```

### **Array elements are numbered, starting with zero. [This thing called indexing]**

* We can get an element by its number in square brackets:

```js
0 1 2
let colors = ['Red', 'Yellow', 'Green'];

console.log( colors[0] ); // Red
console.log( colors[1] ); // Yellow
console.log( colors[2] ); // Green
```
* We can replace an element:

```js
0 1 2
colors[2] = 'Blue'; // now ['Red', 'Yellow', 'Blue']

```
* …Or add a new one to the array:


```js
0 1 2 3
colors[3] = 'Pink'; // now ['Red', 'Yellow', 'Blue', 'Pink']

```
> The total count of the elements in the array is its `length`:

```js
console.log(colors.length);
// 4
```
### The **A**rray can store elements of any type.

* For Example:

```js
// mix of values
let arr = [ 'Apple', { name: 'Fatma' }, true, function() { console.log('hello'); } ];

// get the object at index 1 and then show its name
console.log( arr[1].name ); // Fatma

// get the function at index 3 and run it
arr[3](); // hello

```

Fatmasiam marked this conversation as resolved.
Show resolved Hide resolved
Fatmasiam marked this conversation as resolved.
Show resolved Hide resolved

## <a href='#manipulate-array' id='manipulate-array'>Manipulate Arrays : </a>
- arrays are mutable
**So** array state can be modified after it is created. let's see the following example:

```js
let arr = ["Fatma", "Ala'a"];
arr[2]= "Sama"
arr // ["Fatma", "Ala'a", "Sama"]
```

### **Multidimensional Arrays** : :arrow_double_down:

Arrays can have items that are also arrays. We can use it for multidimensional arrays, for example to store matrices:

```js

let activities = [
/*0*/ /*1*/
/*0*/ ['Working ', 9],
/*1*/ ['Eating ', 2],
/*2*/ ['Commute ', 2],
/*3*/ ['Sleeping', 7],
];

console.log( activities[1] ); // ['Eating ', 2]
console.log( activities[3] ); // ['Sleeping', 7]

console.log( activities[1][1] ); // 2
console.log( activities[0][0] ); // Working
console.log( activities[3][0] ); // Sleeping

activities[4] = ['Study ', 10];

// now
activities = [
["Working ", 9]
["Eating ", 2]
["Commute ", 2]
["Sleeping", 7]
["Study ", 10]
] ;

```
13 changes: 13 additions & 0 deletions coursebook/session-16/homework.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Homework


### Your homework for Arrays session is to write a calculator function that takes at least three parameters and does some mathematical operations:
```js
function calculator([num, op, num, op, num,]) {
// Your Code goes here
};

calculator([2, '+' , 4]); // 2 + 4 = 6
calculator([2, '+', 4, '-', 1, '*', 3 ]) // 2 + 4 - (1 * 3) = 3
```
### Feel free to rename the function and parameters as you like.
10 changes: 10 additions & 0 deletions coursebook/session-16/learning-outcomes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Learning Outcomes

- know and understand Arrays in js:
- Create an Array.
- Array length [how many items on it]
- Access (index into) an Array item.
- Loop over an array by indexes.

- know and understand some Arrays method:
- map, forEach, reduce, filter, sort, pop, push, shift, unshift, join, split
121 changes: 121 additions & 0 deletions coursebook/session-16/loops.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
## <a href='#loops' id='loops'>Loops: while and for </a>
Fatmasiam marked this conversation as resolved.
Show resolved Hide resolved

**Author**: [@Fatmasiam](https://github.com/Fatmasiam)
----
As we learned previously in the [loop](../session-13/loops.md) session

>Loops are handy, if you want to run the same code over and over again, each time with a different value.
We often need to repeat actions.
For example, outputting goods from a list one after another or just running the same code for each number from 1 to 10.
Loops are a way to repeat the same code multiple times.

# **NOW** How loops work with arrays:

## The **“while”** loop:

```js
let colors = ['Red', 'Yellow', 'Orange'];
let i =0;
while (i < colors.length) { // i shows 0, then 1, then 2
console.log( colors[i] ); // this will print the console for colors[0], colors[1], colors[2]
i++;
}
```

A single execution of the loop body is called an _iteration_. The **loop** in the example above makes three _iterations_.

**If** `i++` was missing from the example above, the loop would repeat (in theory) forever.
In practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process.

> The following example uses the while loop statement to add 5 random numbers between 0 and 10 to an array:
```js
// create an array of five random number between 1 and 10
let randomNumbers = [];
let count = 0;
const size = 10;

while(count < size) {
randomNumbers.push(Math.round(Math.random() * 10));
count++;
console.log('The current size of the array is ' + count);
}

console.log(randomNumbers);

```

In this example: :arrow_double_up:
* First, declare and initialize an array.
* Second, add a random number between 0 and 10 in each loop iteration inside the `while` statement. If the value of the `count` equals the value of the `size` variable, the loop stops.


## The **“do…while”** loop

The loop will first execute the body, then check the condition, and, while it’s truthy, execute it again and again.

**For example:**

```js
let alpha = ['A', 'B'];
let i = 0;
do {
console.log(alpha[i]); // print the alpha[0], alpha[1]
i++;
} while (i < alpha.length);

```
**Refreshing Question** :keycap_star: ==> separate[explain] the work for the previous example if the condition will `i <= alpha.length`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could this be something like this

Suggested change
**Refreshing Question** :keycap_star: ==> separate[explain] the work for the previous example if the condition will `i <= alpha.length`
**Refreshing Question** :keycap_star: what will happen if the condition was `i <= alpha.length`



## The **“for”** loop
The for loop is more complex, but it’s also the most commonly used loop.

```js
let names = ['Fiona','Sama', 'Diana'];
/*begin*/ /*condition*/ /*step*/
for (let i = 0; i < names.length; i++) { // i shows 0, then 1, then 2
console.log(names[i]); // names[0], names[1], names[2]
}

```
Here’s exactly what happens in our case:

```js
// for (let i = 0; i < names.length; i++) console.log(names[i])

// run begin
let i = 0
// if condition → run body and run step
/* i = 0*/
if (i < names.length) { console.log(names[0]); i++ }

// if condition → run body and run step
/* i = 1*/
if (i < names.length) { console.log(names[1]); i++ }

// if condition → run body and run step
/* i = 2*/
if (i < names.length) { console.log(names[2]); i++ }

/* i = 3*/
// ...finish, because now i == 3

```



# Summary
### We covered 3 types of loops:

* `while` – The condition is checked before each iteration.
* `do..while` – The condition is checked after each iteration.
* `for (;;)` – The condition is checked before each iteration, additional settings available.
*
To make an “infinite” loop, usually the `while(true)` construct is used. Such a loop, just like any other, can be stopped with the `break` directive.

If we don’t want to do anything in the current iteration and would like to forward to the next one, we can use the `continue` directive.


# Let's have a quick exercise [Reverse String](https://leetcode.com/problems/reverse-string/)


5 changes: 5 additions & 0 deletions coursebook/session-16/research.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Research:

* `reverse` method
* `concat` method
* `splice` and `slice` methods
6 changes: 6 additions & 0 deletions coursebook/session-16/resources.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# **A**dditional **R**esources:

* [arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
* [Indexed collections](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections)
* [Loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#break_statement)
* [Array Loops](https://medium.com/better-programming/how-to-manipulate-and-iterate-arrays-in-javascript-3a0eb819b662)