-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi_Array.js
More file actions
444 lines (336 loc) · 17.5 KB
/
Copy pathi_Array.js
File metadata and controls
444 lines (336 loc) · 17.5 KB
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// ============================================================
// JavaScript Array Methods — Complete Guide
// Covers: Mutating | Non-Mutating | Higher-Order | ES13+
// ============================================================
// ------------------------------------------------------------
// Creating an Array [ES3 | 1999]
// ------------------------------------------------------------
const arr1 = [1, 2, 3, 4, 5]; // Array literal
const arr2 = new Array(1, 2, 3, 4, 5); // Array constructor
const arr3 = []; // Empty array
// ============================================================
// MUTATING METHODS — Modifies the Original Array
// ============================================================
// 1. push() [ES3 | 1999]
// Adds one or more elements to the END of array
// Returns: new length of the array
const numbers = [10, 20, 30, 40];
numbers.push(50, 60);
// console.log(numbers); // [10, 20, 30, 40, 50, 60]
// 2. pop() [ES3 | 1999]
// Removes the LAST element from array
// Returns: the removed element
const fruits = ['apple', 'banana', 'cherry', 'date'];
fruits.pop();
// console.log(fruits); // ['apple', 'banana', 'cherry']
// 3. unshift() [ES3 | 1999]
// Adds one or more elements to the BEGINNING of array
// Returns: new length of the array
const colors = ['blue', 'green', 'yellow'];
colors.unshift('red', 'orange');
// console.log(colors); // ['red', 'orange', 'blue', 'green', 'yellow']
// 4. shift() [ES3 | 1999]
// Removes the FIRST element from array
// Returns: the removed element
const animals = ['lion', 'tiger', 'elephant', 'giraffe'];
animals.shift();
// console.log(animals); // ['tiger', 'elephant', 'giraffe']
// 5. reverse() [ES1 | 1997]
// Reverses the order of elements IN PLACE
// Returns: the modified array
// Note: use toReversed() (ES14) if you want a new array
const letters = ['a', 'b', 'c', 'd'];
letters.reverse();
// console.log(letters); // ['d', 'c', 'b', 'a']
// 6. splice() [ES3 | 1999]
// Add or Remove elements at a specific index
// Syntax: splice(startIndex, deleteCount, ...itemsToAdd)
// Returns: array of removed elements
// Note: use toSpliced() (ES14) if you want a new array
const cities = ['New York', 'London', 'Paris', 'Tokyo'];
cities.splice(1, 2, 'Berlin', 'Rome'); // remove 2, add 2
// console.log(cities); // ['New York', 'Berlin', 'Rome', 'Tokyo']
cities.splice(2, 0, 'Madrid'); // insert without removing
// console.log(cities); // ['New York', 'Berlin', 'Madrid', 'Rome', 'Tokyo']
// 7. sort() [ES1 | 1997]
// Sorts elements IN PLACE
// Default: lexicographic (string) order — always pass compareFn for numbers!
// Returns: the sorted array
// Note: use toSorted() (ES14) if you want a new array
const scores = [45, 5, 12, 89, 23];
scores.sort();
// console.log(scores); // [12, 23, 45, 5, 89] ← string sort, be careful!
scores.sort(function(a, b) { return a - b; }); // old way — numeric ascending
scores.sort((a, b) => a - b); // modern way — numeric ascending
// console.log(scores); // [5, 12, 23, 45, 89]
scores.sort((a, b) => b - a); // numeric descending
// console.log(scores); // [89, 45, 23, 12, 5]
const names = ['John', 'Anna', 'Zara', 'Mike'];
names.sort();
// console.log(names); // ['Anna', 'John', 'Mike', 'Zara']
// 8. fill() [ES6 | 2015]
// Fills all or part of array with a static value
// Syntax: fill(value, startIndex, endIndex)
// Returns: the modified array
const filled = [1, 2, 3, 4, 5];
filled.fill(0, 2, 4); // fill 0 from index 2 to 3
// console.log(filled); // [1, 2, 0, 0, 5]
filled.fill(9); // fill entire array
// console.log(filled); // [9, 9, 9, 9, 9]
// ============================================================
// NON-MUTATING METHODS — Returns New Array / Value
// ============================================================
const arr = [11, 12, 13, 14, 15];
// 1. concat() [ES3 | 1999]
// Joins two or more arrays together
// Returns: a new merged array
const arr4 = [16, 17, 18];
// console.log(arr.concat(arr4)); // [11, 12, 13, 14, 15, 16, 17, 18]
// Modern alternative using spread (ES6) ✨
// console.log([...arr, ...arr4]); // [11, 12, 13, 14, 15, 16, 17, 18]
// 2. slice() [ES3 | 1999]
// Extracts a portion of the array
// Syntax: slice(startIndex, endIndex) — endIndex NOT included
// Returns: a new array
// console.log(arr.slice(0, 3)); // [11, 12, 13]
// console.log(arr.slice(2)); // [13, 14, 15]
// console.log(arr.slice(-2)); // [14, 15] ← negative index works!
// 3. includes() [ES7 | 2016]
// Checks if an element exists in the array
// Returns: true or false
// Note: works with NaN too, unlike indexOf()
// console.log(arr.includes(13)); // true
// console.log(arr.includes(9)); // false
// console.log([1, NaN].includes(NaN)); // true ← indexOf can't do this!
// Old way before ES7
// console.log(arr.indexOf(13) !== -1); // true ← ugly but was the only way
// 4. indexOf() [ES5 | 2009]
// Returns the FIRST index of an element
// Returns: index number, or -1 if not found
// console.log(arr.indexOf(13)); // 2
// console.log(arr.indexOf(99)); // -1
// 5. lastIndexOf() [ES5 | 2009]
// Returns the LAST index of an element
// Returns: index number, or -1 if not found
const dupes = [11, 12, 13, 12, 11];
// console.log(dupes.lastIndexOf(12)); // 3
// console.log(dupes.lastIndexOf(99)); // -1
// 6. toString() [ES1 | 1997]
// Converts array to a comma-separated string
// Returns: string
// console.log(arr.toString()); // "11,12,13,14,15"
// 7. join() [ES1 | 1997]
// Joins all elements with a custom separator
// Returns: string
// console.log(arr.join(' ')); // "11 12 13 14 15"
// console.log(arr.join(' - ')); // "11 - 12 - 13 - 14 - 15"
// console.log(arr.join('')); // "1112131415"
// 8. flat() [ES10 | 2019]
// Flattens nested arrays by given depth
// Returns: new flattened array
const nested = [1, [2, 3], [4, [5, 6]]];
// console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]] ← 1 level deep (default)
// console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6] ← 2 levels deep
// console.log(nested.flat(Infinity)); // [1, 2, 3, 4, 5, 6] ← all levels
// Old way before ES10
// console.log([].concat(...nested)); // manually flatten 1 level
// 9. flatMap() [ES10 | 2019]
// Maps each element then flattens result by 1 level
// Returns: new array (map + flat in one shot)
const sentences = ["Hello World", "ES10 Rocks"];
// console.log(sentences.flatMap(s => s.split(" "))); // ["Hello", "World", "ES10", "Rocks"]
// Old way before ES10
// console.log([].concat(...sentences.map(s => s.split(" ")))); // same result, messy
// 10. Array.from() [ES6 | 2015]
// Creates a new array from an array-like or iterable
// Returns: new array
// console.log(Array.from("hello")); // ['h', 'e', 'l', 'l', 'o']
// console.log(Array.from({length: 3}, (_, i) => i + 1)); // [1, 2, 3]
// console.log(Array.from(new Set([1, 2, 2, 3]))); // [1, 2, 3] ← remove dupes
// 11. Array.of() [ES6 | 2015]
// Creates an array from given arguments
// Returns: new array
// Note: fixes the confusing behavior of new Array()
// console.log(Array.of(1, 2, 3)); // [1, 2, 3]
// console.log(Array.of(7)); // [7] ← just one element
// console.log(new Array(7)); // [,,,,,,,] ← 7 empty slots! (old bug)
// ============================================================
// HIGHER-ORDER FUNCTIONS
// ============================================================
const hArr = [11, 12, 13, 14, 15];
// 1. forEach() [ES5 | 2009]
// Executes a function for each element
// Returns: nothing (undefined)
// Note: cannot be stopped with break — use for...of if you need that
hArr.forEach(function(x) { // old way
// console.log(x);
});
hArr.forEach(x => { // modern way
// console.log(x); // 11, 12, 13, 14, 15 (one per line)
});
// 2. map() [ES5 | 2009]
// Creates a new array by transforming each element
// Returns: new array of same length
// console.log(hArr.map(function(x) { return x - 10; })); // [1, 2, 3, 4, 5] ← old way
// console.log(hArr.map(x => x - 10)); // [1, 2, 3, 4, 5]
// console.log(hArr.map(x => x * 2)); // [22, 24, 26, 28, 30]
// 3. filter() [ES5 | 2009]
// Creates a new array with elements that pass a condition
// Returns: new array (can be smaller than original)
// console.log(hArr.filter(function(x) { return x > 12; })); // [13, 14, 15] ← old way
// console.log(hArr.filter(x => x > 12)); // [13, 14, 15]
// console.log(hArr.filter(x => x % 2 === 0)); // [12, 14]
// 4. reduce() [ES5 | 2009]
// Reduces array to a single value using accumulator
// Syntax: reduce(callback, initialValue)
// Returns: final accumulated value
// console.log(hArr.reduce(function(acc, item) { return acc + item; }, 0)); // 65 ← old way
// console.log(hArr.reduce((acc, item) => acc + item, 0)); // 65 ← sum
// console.log(hArr.reduce((acc, item) => acc * item, 1)); // 3603600 ← product
// reduce to find max
// console.log(hArr.reduce((max, x) => x > max ? x : max, -Infinity)); // 15
// 5. find() [ES6 | 2015]
// Returns the FIRST element matching condition
// Returns: element or undefined
// console.log(hArr.find(x => x > 12)); // 13
// console.log(hArr.find(x => x > 99)); // undefined
// Old way before ES6
// console.log(hArr.filter(x => x > 12)[0]); // 13 ← worked but wasteful
// 6. findIndex() [ES6 | 2015]
// Returns the INDEX of the first matching element
// Returns: index number, or -1 if not found
// console.log(hArr.findIndex(x => x > 12)); // 2
// console.log(hArr.findIndex(x => x > 99)); // -1
// Old way before ES6
// var idx = -1;
// for (var i = 0; i < hArr.length; i++) { if (hArr[i] > 12) { idx = i; break; } }
// console.log(idx); // 2
// 7. every() [ES5 | 2009]
// Checks if ALL elements satisfy a condition
// Returns: true or false
// console.log(hArr.every(x => x > 10)); // true
// console.log(hArr.every(x => x > 11)); // false
// 8. some() [ES5 | 2009]
// Checks if AT LEAST ONE element satisfies a condition
// Returns: true or false
// console.log(hArr.some(x => x > 14)); // true
// console.log(hArr.some(x => x > 15)); // false
// 9. reduceRight() [ES5 | 2009]
// Same as reduce() but iterates from RIGHT to LEFT
// Returns: final accumulated value
const words = ["World", "Hello"];
// console.log(words.reduceRight((acc, w) => acc + " " + w)); // "Hello World"
// ============================================================
// ES13+ MODERN ARRAY METHODS
// ============================================================
// 1. at() [ES13 | 2022]
// Access element by index — supports negative indexing!
// Returns: element at given index
// Note: works on strings too
const modArr = [10, 20, 30, 40, 50];
// console.log(modArr.at(0)); // 10
// console.log(modArr.at(-1)); // 50 ← last item
// console.log(modArr.at(-2)); // 40 ← second last
// console.log("Hello".at(-1)); // "o" ← works on strings too!
// Old way before ES13
// console.log(modArr[modArr.length - 1]); // 50 ← ugly
// 2. findLast() [ES13 | 2022]
// Returns the LAST element matching condition
// Returns: element or undefined
const fnums = [1, 2, 3, 4, 5, 4, 3];
// console.log(fnums.findLast(n => n > 3)); // 4
// Old way before ES13
// console.log([...fnums].reverse().find(n => n > 3)); // 4 ← clone + reverse, messy
// 3. findLastIndex() [ES13 | 2022]
// Returns the INDEX of the last matching element
// Returns: index number, or -1 if not found
// console.log(fnums.findLastIndex(n => n > 3)); // 5
// Old way before ES13
// var lastIdx = -1;
// for (var i = fnums.length - 1; i >= 0; i--) { if (fnums[i] > 3) { lastIdx = i; break; } }
// console.log(lastIdx); // 5
// 4. toSorted() [ES14 | 2023]
// Sorts array WITHOUT mutating the original
// Returns: new sorted array (immutable version of sort())
const original = [3, 1, 4, 1, 5];
const toSortedAsc = original.toSorted();
const toSortedDesc = original.toSorted((a, b) => b - a);
// console.log(original); // [3, 1, 4, 1, 5] ← unchanged!
// console.log(toSortedAsc); // [1, 1, 3, 4, 5]
// console.log(toSortedDesc); // [5, 4, 3, 1, 1]
// Old way before ES14 (had to clone first)
// console.log([...original].sort((a, b) => a - b)); // [1, 1, 3, 4, 5]
// 5. toReversed() [ES14 | 2023]
// Reverses array WITHOUT mutating the original
// Returns: new reversed array (immutable version of reverse())
const toReversed = original.toReversed();
// console.log(original); // [3, 1, 4, 1, 5] ← unchanged!
// console.log(toReversed); // [5, 1, 4, 1, 3]
// Old way before ES14 (had to clone first)
// console.log([...original].reverse()); // [5, 1, 4, 1, 3]
// 6. toSpliced() [ES14 | 2023]
// Splices array WITHOUT mutating the original
// Returns: new array (immutable version of splice())
const toSpliced = original.toSpliced(1, 2, 9);
// console.log(original); // [3, 1, 4, 1, 5] ← unchanged!
// console.log(toSpliced); // [3, 9, 1, 5]
// Old way before ES14 (had to clone first)
// const copy = [...original]; copy.splice(1, 2, 9);
// console.log(copy); // [3, 9, 1, 5]
// 7. with() [ES14 | 2023]
// Replaces ONE element by index WITHOUT mutating the original
// Returns: new array (negative index supported)
const withArr = [1, 2, 3, 4, 5];
const withNew = withArr.with(2, 99);
// console.log(withArr); // [1, 2, 3, 4, 5] ← unchanged!
// console.log(withNew); // [1, 2, 99, 4, 5]
// console.log(withArr.with(-1, 0)); // [1, 2, 3, 4, 0] ← negative index!
// Old way before ES14
// const copy = [...withArr]; copy[2] = 99;
// console.log(copy); // [1, 2, 99, 4, 5]
// ============================================================
// QUICK REFERENCE CHEAT SHEET
// ============================================================
// MUTATING (changes original) VERSION
// ─────────────────────────────────────────────────
// push() → add to end ES3
// pop() → remove from end ES3
// unshift() → add to start ES3
// shift() → remove from start ES3
// reverse() → reverse in place ES1
// splice() → add/remove at index ES3
// sort() → sort in place ES1
// fill() → fill with value ES6
// NON-MUTATING (returns new) VERSION
// ─────────────────────────────────────────────────
// concat() → merge arrays ES3
// slice() → extract portion ES3
// includes() → check existence ES7
// indexOf() → find first index ES5
// lastIndexOf() → find last index ES5
// toString() → convert to string ES1
// join() → join with separator ES1
// flat() → flatten nested ES10
// flatMap() → map + flatten ES10
// Array.from() → from iterable ES6
// Array.of() → from arguments ES6
// HIGHER-ORDER VERSION
// ─────────────────────────────────────────────────
// forEach() → iterate ES5
// map() → transform each ES5
// filter() → filter by condition ES5
// reduce() → accumulate to value ES5
// reduceRight() → reduce from right ES5
// find() → first match ES6
// findIndex() → index of first match ES6
// every() → all match? ES5
// some() → any match? ES5
// ES13+ MODERN (immutable alternatives) VERSION
// ─────────────────────────────────────────────────
// at() → index (negative ok) ES13
// findLast() → last match ES13
// findLastIndex()→ index of last match ES13
// toSorted() → sort (immutable) ES14
// toReversed() → reverse (immutable) ES14
// toSpliced() → splice (immutable) ES14
// with() → replace one (immutable) ES14