cover | coverY | description |
---|---|---|
.gitbook/assets/reduce (1).png |
0 |
Github Repo: https://github.com/bgoonz/Array-Methods-Lesson |
map([๐ฝ, ๐ฎ, ๐], cook) => [๐ฟ, ๐, ๐ณ]
filter([๐ฟ, ๐, ๐ณ], isVegetarian) => [๐ฟ, ๐ณ]
reduce([๐ฟ, ๐ณ], eat) => ๐ฉ
{% file src=".gitbook/assets/array-methods (1).zip" %} download-js-files {% endfile %}
{% embed url="https://bryan-guner.gitbook.io/array-methods-lesson" %} Public Web Address {% endembed %}
{% embed url="https://github.com/bgoonz/Array-Methods-Lesson" %} Corresponding Github Repository {% endembed %}
{% embed url="https://replit.com/@bgoonz/array-methods#index.js" %}
map([๐ฝ, ๐ฎ, ๐], cook) => [๐ฟ, ๐, ๐ณ]
filter([๐ฟ, ๐, ๐ณ], isVegetarian) => [๐ฟ, ๐ณ]
reduce([๐ฟ, ๐ณ], eat) => ๐ฉ
- Mutability
- Array Basics
- ๐ Background
- Callback Functions
- Higher Order Functions
- ๐ง Difference Between Functions & Methods...
- โก Fat Arrow Syntax
// Mutating
push() // Insert an element at the end
pop() // Remove an element from the end
unshift() // Inserts an element in the beginning
shift() // Remove first element
// Iterating
forEach() // Iterates an array
filter() // Iterates an array and result is filtered array
map() // Iterates an array and result is new array
reduce() // "Reduces" the array into single value (accumulator)
// Others
slice() // Returns desired elements in a new array
concat() // Append one or more arrays with given array
JavaScript Arrays are a very flexible data structure and used as lists, stacks, queues, tuples (e.g. pairs), etc. Some
Using Arrays
Creating Arrays, reading and writing elements:
const arr = ['a', 'b', 'c']; // Array literal
assert.deepEqual(
arr,
[
'a',
'b',
'c', // trailing commas are ignored
]
);
assert.equal(
arr.length, 3 // number of elements
);
assert.equal(
arr[0], 'a' // read (negative indices donโt work)
);
assert.equal(
arr.at(-1), 'c' // read (negative indices work)
);
arr[0] = 'x'; // write
assert.deepEqual(
arr, ['x', 'b', 'c']
);
The lengths of Arrays, adding elements:
const arr = ['a'];
assert.equal(
arr.length, 1 // number of elements
);
arr.push('b'); // add an element (preferred)
assert.deepEqual(
arr, ['a', 'b']
);
arr[arr.length] = 'c'; // add an element (alternative)
assert.deepEqual(
arr, ['a', 'b', 'c']
);
arr.length = 1; // remove elements
assert.deepEqual(
arr, ['a']
);
Concatenating Arrays via spreading (...
):
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e', 'f'];
assert.deepEqual(
[...arr1, ...arr2, ...arr3, 'g'],
['a', 'b', 'c', 'd', 'e', 'f', 'g']
);
Clearing Arrays (removing all elements):
// Affects everyone referring to the Array
const arr1 = ['a', 'b', 'c'];
arr1.length = 0;
assert.deepEqual(
arr1, []
);
// Does not affect others referring to the Array
let arr2 = ['a', 'b', 'c'];
arr2 = [];
assert.deepEqual(
arr2, []
);
Looping over elements:
const arr = ['a', 'b', 'c'];
for (const value of arr) {
console.log(value);
}
// Output:
// 'a'
// 'b'
// 'c'
Looping over key-element pairs:
const arr = ['a', 'b', 'c'];
for (const [index, value] of arr.entries()) {
console.log(index, value);
}
// Output:
// 0, 'a'
// 1, 'b'
// 2, 'c'
Creating and filling Arrays when we canโt use Array literals (e.g. because we donโt know their lengths in advance or they are too large):
const four = 4;
// Empty Array that weโll fill later
assert.deepEqual(
new Array(four),
[ , , , ,] // four holes; last comma is ignored
);
// An Array filled with a primitive value
assert.deepEqual(
new Array(four).fill(0),
[0, 0, 0, 0]
);
// An Array filled with objects
// Why not .fill()? Weโd get single object, shared multiple times.
assert.deepEqual(
Array.from({length: four}, () => ({})),
[{}, {}, {}, {}]
);
// A range of integers
assert.deepEqual(
Array.from({length: four}, (_, i) => i),
[0, 1, 2, 3]
);
Array methods
Deriving a new Array from an existing Array:
> ['โ ','โ','โฒ'].slice(1, 3)
['โ','โฒ']
> ['โ ','โ','โ '].filter(x => x==='โ ')
['โ ','โ ']
> ['โฒ','โ'].map(x => x+x)
['โฒโฒ','โโ']
> ['โฒ','โ'].flatMap(x => [x,x])
['โฒ','โฒ','โ','โ']
Removing an Array element at a given index:
const arr = ['โ ','โ','โฒ'];
assert.deepEqual(
arr.filter((_, index) => index !== 1),
['โ ','โฒ']
);
assert.deepEqual(
arr, ['โ ','โ','โฒ'] // .filter() is non-destructive
);
arr.splice(1, 1); // start at 1, delete 1 element
assert.deepEqual(
arr, ['โ ','โฒ'] // .splice() is destructive
);
Computing a summary of an Array:
> ['โ ','โ','โฒ'].some(x => x==='โ')
true
> ['โ ','โ','โฒ'].every(x => x==='โ')
false
> ['โ ','โ','โฒ'].join('-')
'โ -โ-โฒ'
> ['โ ','โ'].reduce((result,x) => result+x, 'โฒ')
'โฒโ โ'
> ['โ ','โ'].reduceRight((result,x) => result+x, 'โฒ')
'โฒโโ '
Changing all of an Array (the input Array is modified and returned):
> ['โ ','โ','โฒ'].fill('โ')
['โ','โ','โ']
> ['โ ','โ','โฒ'].reverse()
['โฒ','โ','โ ']
> ['โ ','โ','โ '].sort()
['โ ','โ ','โ']
Finding Array elements:
> ['โ ','โ','โ '].includes('โ ')
true
> ['โ ','โ','โ '].indexOf('โ ')
0
> ['โ ','โ','โ '].lastIndexOf('โ ')
2
> ['โ ','โ','โ '].find(x => x==='โ ')
'โ '
> ['โ ','โ','โ '].findIndex(x => x==='โ ')
0
Listing elements (Array.from()
is needed because the methods return iterables, not Arrays):
> Array.from(['โ ','โ','โฒ'].keys())
[0,1,2]
> Array.from(['โ ','โ','โฒ'].entries())
[[0,'โ '],[1,'โ'],[2,'โฒ']]
Adding or removing an element at either end of an Array:
const arr1 = ['โ ','โ'];
arr1.push('โฒ');
assert.deepEqual(
arr1, ['โ ','โ','โฒ']
);
const arr2 = ['โ ','โ','โฒ'];
arr2.pop();
assert.deepEqual(
arr2, ['โ ','โ']
);
const arr3 = ['โ ','โ'];
arr3.unshift('โฒ');
assert.deepEqual(
arr3, ['โฒ','โ ','โ']
);
const arr4 = ['โฒ','โ ','โ'];
arr4.shift();
assert.deepEqual(
arr4, ['โ ','โ']
);