Skip to content

Commit f03c0f3

Browse files
committed
Initial commit
0 parents  commit f03c0f3

File tree

14 files changed

+7040
-0
lines changed

14 files changed

+7040
-0
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
node_modules
2+
.next
3+
4+
# No Cheating!
5+
quiz-solutions.test.js

README.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Array Methods in JavaScript
2+
3+
Shift Lunch and Learn 7-26-19
4+
5+
## Overview
6+
7+
- Why do native array methods matter?
8+
- Common array methods and what they do
9+
- Determine which array method to use in which situation
10+
- Practical (sort of) examples in React, etc
11+
12+
## Why do array methods matter?
13+
14+
- _Declarative_ vs _imperative_
15+
- "Do this thing" vs "execute these steps"
16+
- Typically more succinct, more grok-able syntax
17+
18+
```js
19+
function getResults(arr) {
20+
const results = [];
21+
22+
for (let i = 0; i < arr.length; i++) {
23+
const element = arr[i];
24+
25+
if (someValidationFunction(element)) {
26+
results.push(element);
27+
}
28+
}
29+
30+
return results;
31+
}
32+
33+
// vs
34+
35+
function getResults(arr) {
36+
return arr.filter(someValidationFunction);
37+
}
38+
```
39+
40+
- Chainable
41+
- Encourage reusability and composability
42+
- Standardized - handle edge cases, usable across environments
43+
44+
## Common Array Methods
45+
46+
- forEach
47+
- map
48+
- filter
49+
- reduce
50+
- some
51+
- every
52+
- find
53+
- includes
54+
55+
Let's look at code!
56+
57+
## When do I use which Array method?
58+
59+
Use [this](https://sdras.github.io/array-explorer/)
60+
61+
tl;dr
62+
|Method|When to Use|
63+
|------|-----------|
64+
|forEach|Run some code for every element, don't care about return value|
65+
|map|Run some code for every element, and track every return value separately|
66+
|filter|Only want part of the array that satisies a condition|
67+
|reduce|Run some code for every element, and "boil it down" to a single value at the end|
68+
|some|Is there at least one element that satisfies this condition?|
69+
|every|Do all elements satify this condition?|
70+
|find|Give me the first element that satisfies this condition|
71+
|inclues|Does this array contain this exact value?|
72+
73+
## Quick React Demo
74+
75+
Note: Extremely contrived and bad
76+
77+
## Questions?
78+
79+
## Additional Reading
80+
81+
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
82+
- https://sdras.github.io/array-explorer/
83+
- https://syntax.fm/show/043/20-javascript-array-and-object-methods-to-make-you-a-better-developer

filter.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// `Array#filter` executes a given callback on an array, returning a new array of all
2+
// elements for which the callback returns `true`
3+
4+
const numbers = [1, 2, 3, 4, 5, 6];
5+
const evenNumbers = numbers.filter(number => number % 2 === 0);
6+
console.log(evenNumbers);
7+
8+
// Let's write our own!
9+
function myFilter(array, callback) {}
10+
11+
console.log(myFilter([2, 4, 5, 6], num => num % 2 === 0));

forEach.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// The Array#forEach method accepts a callback function that gets executed for each element of
2+
// the given array. The callback is passed the element and the current index as arguments.
3+
4+
// The callback passed to `forEach` doesn't return anything, and the actual `forEach` call doesn't
5+
// return anything either. Check out the TypeScript hints for this block of and you'll see both the
6+
// `forEach` method and its callback argument are typed to return `void`.
7+
8+
const numbers = [1, 2, 3, 4, 5];
9+
10+
numbers.forEach(element => {
11+
console.log(`Current element is ${element}`);
12+
});
13+
14+
// Use `forEach` to mutate the original array if necessary
15+
const mutateMe = [{}, {}];
16+
17+
mutateMe.forEach((element, i) => {
18+
element.index = i;
19+
});
20+
21+
console.log(mutateMe);
22+
23+
// forEach is also useful for updating some outer scope variable that isn't
24+
// directly represented in the given array
25+
let myFavoriteColor = "blue";
26+
27+
[{ color: "green", rank: 2 }, { color: "red", rank: 1 }].forEach(element => {
28+
if (element.rank === 1) {
29+
myFavoriteColor = element.color;
30+
}
31+
});
32+
33+
console.log(myFavoriteColor);
34+
35+
// Let's implement our own forEach method!
36+
function myForEach(array, callback) {}
37+
38+
myForEach(numbers, element => console.log(element * 2));

map.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Array#map is similar to `.forEach` in that it executes a given callback for every element in
2+
// an array, but `.map` actually returns a value. The return value of `.map` is a new array of all
3+
// the return values returned by the callback.
4+
5+
// Double each number in the array - get back an array of the doubled numbers
6+
const numbers = [1, 2, 3, 4, 5];
7+
const doubledNumbers = numbers.map(number => number * 2);
8+
9+
// Or, without shorthand
10+
const doubledNumbers2 = numbers.map(number => {
11+
return number * 2;
12+
});
13+
14+
console.log(doubledNumbers);
15+
console.log(doubledNumbers2);
16+
17+
// `.map` is great for transforming data into a new structure
18+
const data = [
19+
{ id: 1, is_married: "YES", FIRSTNAME: "John", last: "Doe" },
20+
{ id: 2, is_married: "NO", FIRSTNAME: "Jane", last: "Doe" }
21+
];
22+
23+
const sanitizedData = data.map(record => {
24+
return {
25+
id: record.id,
26+
isMarried: record.is_married === "YES",
27+
firstName: record.FIRSTNAME,
28+
lastName: record.last
29+
};
30+
});
31+
32+
console.log(sanitizedData);
33+
34+
// Let's write our own `.map`!
35+
function myMap(array, callback) {}
36+
37+
const numbersAgain = [4, 5, 6, 7];
38+
const squaredNumbers = myMap(numbersAgain, number => number * number);
39+
console.log(squaredNumbers);

next-env.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/// <reference types="next" />
2+
/// <reference types="next/types/global" />

others.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Lightning round: here's a few array methods that don't deserve their own file
2+
3+
// `.some` - return true as long as at least one element satisfies the condition returned by the callback
4+
const hasEvenNumber = [1, 2, 3, 4].some(num => num % 2 === 0);
5+
console.log(hasEvenNumber);
6+
7+
// `.every` - return true as long as ALL elements satisfy the condition returned by the callback
8+
const allEven = [2, 4, 6, 8].every(num => num % 2 === 0);
9+
console.log(allEven);
10+
11+
// `.find` - return the first value that satifsies the condition returned by the callback
12+
const firstEven = [1, 2, 3, 4].find(num => num % 2 === 0);
13+
console.log(firstEven);
14+
15+
// `.includes` - return true if the value is present in the array
16+
const hasTwo = [1, 2, 3, 4].includes(2);
17+
console.log(hasTwo);

package.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"name": "js-arrays",
3+
"version": "1.0.0",
4+
"main": "index.js",
5+
"license": "MIT",
6+
"dependencies": {
7+
"axios": "^0.19.0",
8+
"next": "^9.0.2",
9+
"react": "^16.8.6",
10+
"react-dom": "^16.8.6"
11+
},
12+
"scripts": {
13+
"start": "next dev",
14+
"test": "jest"
15+
},
16+
"devDependencies": {
17+
"@types/node": "^12.6.8",
18+
"@types/react": "^16.8.23",
19+
"jest": "^24.8.0",
20+
"typescript": "^3.5.3"
21+
}
22+
}

pages/index.tsx

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import React, { useState } from "react";
2+
import axios from "axios";
3+
import { NextPage } from "next";
4+
5+
import { User, GetUsers } from "./types";
6+
7+
interface Props {
8+
users: User[];
9+
}
10+
11+
const IndexPage: NextPage<Props> = ({ users }) => {
12+
const [query, setQuery] = useState<string>("");
13+
14+
// Filter the set of users based on the provided query
15+
const displayedUsers =
16+
query === ""
17+
? users
18+
: users.filter(
19+
user =>
20+
user.name.first.match(new RegExp(query)) ||
21+
user.name.last.match(new RegExp(query))
22+
);
23+
24+
return (
25+
<div className="wrapper">
26+
<h1>List Users</h1>
27+
28+
<label htmlFor="query">Search</label>
29+
<input
30+
type="text"
31+
name="query"
32+
value={query}
33+
onChange={e => {
34+
setQuery(e.target.value);
35+
}}
36+
/>
37+
38+
<ul>
39+
{/* Loop over the set of users and return a JSX Node for each of them */}
40+
{displayedUsers.map(user => (
41+
<li key={user.id.value}>
42+
<img
43+
src={user.picture.thumbnail}
44+
alt={`${user.name.first} ${user.name.last}`}
45+
/>
46+
<h3>
47+
{user.name.first} {user.name.last}
48+
</h3>
49+
</li>
50+
))}
51+
</ul>
52+
53+
<style jsx>{`
54+
ul {
55+
list-style: none;
56+
padding: 0;
57+
display: grid;
58+
grid-template-columns: 1fr 1fr 1fr 1fr;
59+
grid-gap: 10px;
60+
width: 80%;
61+
margin: 25px auto;
62+
}
63+
64+
li {
65+
border: 1px solid #dadada;
66+
border-radius: 10px;
67+
}
68+
69+
label {
70+
display: block;
71+
}
72+
73+
.wrapper {
74+
text-align: center;
75+
}
76+
`}</style>
77+
78+
<style jsx global>
79+
{`
80+
body {
81+
margin: 0;
82+
padding: 0;
83+
font-family: sans-serif;
84+
}
85+
`}
86+
</style>
87+
</div>
88+
);
89+
};
90+
91+
IndexPage.getInitialProps = async () => {
92+
const userUrl = "https://randomuser.me/api?results=25&nat=US";
93+
const response = await axios.get<GetUsers>(userUrl);
94+
95+
return { users: response.data.results };
96+
};
97+
98+
export default IndexPage;

0 commit comments

Comments
 (0)