This repository has been archived by the owner on Jul 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrays-javascript.html
137 lines (130 loc) · 8.37 KB
/
arrays-javascript.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="X-UA-Compatible" content="ie=edge"><meta name="description" content="Arrays in Javascript have many specific methods for modification and analysis. Some are cunfusiong or hard to recall."><!-- Bing --><meta name="msvalidate.01" content="45CBBE1BD8265A2217DFDA630EB8F84A" /><title>Tiny Brain Fans - Arrays (Javascript)</title><link rel="stylesheet" href="tinystyle.css"></head><body>
<main id="main"><article id="content"><h1 id="title">Arrays (Javascript)</h1><p><a href="array.html">Arrays</a> in <a href="javascript.html">Javascript</a> have many specific methods for modification and analysis. Some are cunfusiong or hard to recall.</p>
<h2>Methods</h2>
<h3><code>forEach</code> and other methods[2]</h3>
<p><code>map</code>, <code>filter</code>, <code>forEach</code>, and others take a callback that iterates through each item. However, while <code>map</code>, <code>filter</code> and others return an array based on the return of the callback, <code>forEach</code> does not. For this reason, <code>forEach</code> should be used for <strong>side effects</strong> and <em>not</em> direct modification of the array itself.</p>
<p>The focus of what is going on inside of a <code>map</code> or a <code>filter</code> or whatever is "what is being returned from this function?", whereas the focus of a <code>forEach</code> is "how is the data within this array being used?".</p>
<h3>reduce</h3>
<p><code>reduce</code> will iterate through the items in the array and operate the callback function on each one, passing the previous value's result post-callback. Because of this, <code>reduce</code> can be used to build most array methods from scratch. That being said, usually using the more specific methods and currying them results in more readable code[1].</p>
<p><code>reduce</code> takes up to two params: the callback function, and the initial value.</p>
<h4>Callback</h4>
<p>The callback function can take up to four params:</p>
<ul>
<li><code>previousValue</code> or<code>accumulator</code></li>
<li><code>currentValue</code></li>
<li><code>currentIndex</code></li>
<li><code>array</code></li>
</ul>
<p>The result of this callback function will go into the <code>previousValue</code>/<code>accumulator</code> and then the currentValue will become the next item in the array. At the end of the iteration, the <code>previousValue</code> is what is returned from the <code>reduce</code> function.</p>
<h4>Initial Value</h4>
<p>This value is going to be passed in to the callback function for the first item in the array, where no <code>previousValue</code>/<code>accumulator</code> would otherwise exist.</p>
<p>If no initial value is provided, the <code>previousValue</code>/<code>accumulator</code> will be set to the first item in the array, and the <code>currentValue</code> will be set to the second item in the array.</p>
<h4>Examples</h4>
<h5>Check Condition on All Items</h5>
<p>By setting the callback to require that both the accumulator be true and that the value is evenly divisible by 2, this will check that all values pass the condition. Without the accumulator check, it will only return whether the last item in the list is even.</p>
<pre><code class="language-javascript">const evenArray = [2,4,6,8];
const mixedArray = [2,3,4,5,6];
evenArray.reduce((acc, val) => acc && val % 2 === 0, true); // returns true
mixedArray.reduce((acc, val) => acc && val % 2 === 0, true); // returns false
</code></pre>
<h5>Sum All Items</h5>
<p>This works by initially setting the sum to the first value in the array, and then adding that to each successive value.</p>
<pre><code class="language-javascript">const numbers = [1,2,3,4,5];
numbers.reduce((sum, val) => sum + val); // returns 15
</code></pre>
<h5>Filter Out Odd Numbers</h5>
<pre><code class="language-javascript">const numbers = [1,2,3,4,5];
numbers.reduce((resultArray, val) => {
if (val % 2 === 0) {
resultArray.push(val);
}
return resultArray;
}, []); // returns [2,4];
</code></pre>
<h5>Conditional Map: Return All Values Over 2 Divided By 2</h5>
<pre><code class="language-javascript">const numbers = [1,2,3,4,5];
numbers.reduce((resultArray, val) => {
if (val > 2) {
const newNum = val / 2;
resultArray.push(newNum);
}
return resultArray;
}, []); // returns [1.5, 2, 2.5];
</code></pre>
<h4>When NOT to use <code>reduce</code>[1]</h4>
<p>While <code>reduce</code> can do everything, it's not the best except for fairly straightforward applications, as it is a bit obtuse. <code>filter</code> filters, <code>map</code> maps, <code>reduce</code> does everything. Hard to grok semantically. </p>
<p>For instance, if you had an array that holds properties that you need to decrement, as well as conditionally remove items when that property reaches zero, this <em>could</em> all be done in <code>reduce</code>:</p>
<pre><code class="language-javascript">let numbers = [
{ ticker: 1 },
{ ticker: 3 },
{ ticker: 0 },
{ ticker: 10 },
];
numbers = numbers.reduce((allNumbers, number) => {
// Remove tickers at 0
if (number.ticker === 0) {
return allNumbers;
}
// Decrement ticker
number.ticker--;
allNumbers.push(number);
return allNumbers;
}, []);
</code></pre>
<p>This same thing could be done using <code>filter</code> followed by <code>map</code> in a much more compartmentalized way:</p>
<pre><code class="language-javascript">let numbers = [
{ ticker: 1 },
{ ticker: 3 },
{ ticker: 0 },
{ ticker: 10 },
];
numbers = numbers
// Remove tickers at 0
.filter(number => number.ticker !== 0)
// Decrement ticker
.map(number => {
number.ticker--;
return number;
});
</code></pre>
<p>Each method does a particular thing and <em>only</em> that thing.</p>
<h2>Destructive Methods</h2>
<p>These methods affect the array the method is called upon.</p>
<h3>sort</h3>
<p>The sort function can work with or without a sorting function that sorts <strong>in place</strong>. Without, it will simply convert every value into a string and compare via Unicode point value. With, it follows this formula: <code>.sort(compareFunction)</code>. </p>
<p>From <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort" target="_blank">MDN</a>:</p>
<blockquote>
<p>If <code>compareFunction(a, b)</code> returns a value > than 0, sort <code>b</code> before <code>a</code>. If <code>compareFunction(a, b)</code> returns a value ≤ 0, leave <code>a</code> and <code>b</code> in the same order. </p>
</blockquote>
<p>An example compare function:</p>
<pre><code class="language-javascript">const array = [3,2,4,1];
const compareFunction = (a, b) => {
if (a < b) {
// leave a before b
return -1;
} else if (a > b) {
// place b before a
return 1;
} else { // a === b
// leave a before b
return 0;
}
};
array.sort(compareFunction); // array now equals [1,2,3,4]
</code></pre>
<h3>splice</h3>
<p>Splice works for both removal and insertion of array elements. Splice operates in place and will return whatever elements were spliced from the array.</p>
<p><code>splice(start, deleteCount, [item, ...])</code></p>
<pre><code class="language-javascript">let array = [1,2,3,4];
array.splice(1); // returns [2,3,4]; array now equals [1]
array = [1,2,3,4];
array.splice(1,1); // returns [2]; array now equals [1,3,4]
array = [1,2,3,4];
array.splice(1,1,17); // returns [2]; array now equals [1,17,3,4]
</code></pre>
<h2>References</h2>
<ol>
<li><a href="https://stackoverflow.com/a/36557522/14857724" target="_blank">https://stackoverflow.com/a/36557522/14857724</a></li>
<li><a href="https://scribe.rip/@ntgard/foreach-is-for-side-effects-60fca9f78850" target="_blank">https://scribe.rip/@ntgard/foreach-is-for-side-effects-60fca9f78850</a></li>
</ol>
<p class="last-modified">Last modified: 202206101419</p></article></main><footer><nav><a href="index.html">Sitemap</a></nav><div class="social"><p>Built using <a href="http://codeberg.org/milofultz/swiki" target="_blank" rel="noopener noreferrer">{{SWIKI}}</a></p><p><a href="http://codeberg.org/milofultz/" target="_blank" rel="noopener noreferrer">Codeberg</a></p><p><a href="http://milofultz.com/" target="_blank" rel="noopener noreferrer">milofultz.com</a></p><p><a href="https://merveilles.town/@milofultz" target="_blank" rel="me noopener noreferrer">Mastodon</a></p></div></footer></body></html>