Arrays
## Learning Objectives
- Create and manipulate arrays
- Master array methods (map, filter, reduce, etc.)
- Understand array iteration techniques
## Creating Arrays
```javascript
const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, null, { name: "Alice" }];
const sparse = [1, , 3]; // Has a hole
// Array constructor
const arr = new Array(1, 2, 3); // [1, 2, 3]
const empty = new Array(5); // Creates array with 5 empty slots
```
## Accessing Elements
```javascript
const fruits = ["apple", "banana", "cherry"];
fruits[0]; // "apple"
fruits[2]; // "cherry"
fruits[fruits.length - 1]; // "cherry" (last element)
fruits[10]; // undefined
```
## Array Length
```javascript
const arr = [1, 2, 3];
arr.length; // 3
// Modify length
arr.length = 5; // [1, 2, 3, empty x 2]
arr.length = 2; // [1, 2]
```
## Adding and Removing Elements
```javascript
const fruits = ["apple", "banana"];
// Add to end
fruits.push("cherry"); // ["apple", "banana", "cherry"]
// Add to beginning
fruits.unshift("avocado"); // ["avocado", "apple", "banana", "cherry"]
// Remove from end
const last = fruits.pop(); // "cherry", ["avocado", "apple", "banana"]
// Remove from beginning
const first = fruits.shift(); // "avocado", ["apple", "banana"]
// Remove/insert elements (start, deleteCount, ...items)
fruits.splice(1, 1, "blueberry", "kiwi"); // ["apple", "blueberry", "kiwi", "cherry"]
```
## Iterating Arrays
### for Loop
```javascript
const nums = [1, 2, 3];
for (let i = 0; i < nums.length; i++) {
console.log(nums[i]);
}
```
### forEach
```javascript
const nums = [1, 2, 3];
nums.forEach(function(num, index) {
console.log(`${index}: ${num}`);
});
nums.forEach((num, index) => {
console.log(`${index}: ${num}`);
});
```
### for...of
```javascript
const nums = [1, 2, 3];
for (const num of nums) {
console.log(num);
}
```
## map()
Creates a new array by transforming each element.
```javascript
const nums = [1, 2, 3];
const doubled = nums.map(num => num * 2); // [2, 4, 6]
const objects = nums.map(num => ({ value: num })); // [{value: 1}, {value: 2}, {value: 3}]
```
## filter()
Creates a new array with elements that pass a test.
```javascript
const nums = [1, 2, 3, 4, 5, 6];
const evens = nums.filter(num => num % 2 === 0); // [2, 4, 6]
const greaterThan3 = nums.filter(num => num > 3); // [4, 5, 6]
```
## reduce()
Reduces an array to a single value.
```javascript
const nums = [1, 2, 3, 4];
// Sum all numbers
const sum = nums.reduce((acc, num) => acc + num, 0); // 10
// Find max value
const max = nums.reduce((acc, num) => acc > num ? acc : num, nums[0]); // 4
// Flatten array
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []); // [1, 2, 3, 4, 5, 6]
```
## find(), findIndex(), findLast()
```javascript
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" }
];
// find() - returns first matching element
const user = users.find(u => u.id === 2); // { id: 2, name: "Bob" }
// findIndex() - returns index of first match
const index = users.findIndex(u => u.name === "Charlie"); // 2
// findLast() - returns last matching element (ES2023)
const last = nums.findLast(n => n > 2); // 6
```
## some() and every()
```javascript
const nums = [1, 2, 3, 4, 5];
// some() - true if ANY element passes test
const hasEven = nums.some(num => num % 2 === 0); // true
// every() - true if ALL elements pass test
const allPositive = nums.every(num => num > 0); // true
```
## includes()
```javascript
const fruits = ["apple", "banana", "cherry"];
fruits.includes("apple"); // true
fruits.includes("grape"); // false
fruits.includes("banana", 2); // false (starting from index 2)
```
## indexOf() and lastIndexOf()
```javascript
const nums = [1, 2, 3, 2, 1];
nums.indexOf(2); // 1
nums.lastIndexOf(2); // 3
nums.indexOf(5); // -1 (not found)
```
## sort() and reverse()
```javascript
const fruits = ["banana", "apple", "cherry"];
fruits.sort(); // ["apple", "banana", "cherry"]
fruits.reverse(); // ["cherry", "banana", "apple"]
// Numeric sort
const nums = [10, 1, 21, 2];
nums.sort((a, b) => a - b); // [1, 2, 10, 21]
nums.sort((a, b) => b - a); // [21, 10, 2, 1]
```
## slice()
Returns a shallow copy of a portion of an array.
```javascript
const nums = [1, 2, 3, 4, 5];
nums.slice(1, 3); // [2, 3] (start, end-1)
nums.slice(2); // [3, 4, 5] (from index to end)
nums.slice(-2); // [4, 5] (last 2 elements)
nums.slice(); // [1, 2, 3, 4, 5] (shallow copy)
```
## concat()
```javascript
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
arr1.concat(arr2); // [1, 2, 3, 4]
arr1.concat(arr2, arr3); // [1, 2, 3, 4, 5, 6]
```
## flat() and flatMap()
```javascript
// flat() - flattens nested arrays
const nested = [1, [2, [3, [4]]]];
nested.flat(); // [1, 2, [3, [4]]] (default depth 1)
nested.flat(2); // [1, 2, 3, [4]]
nested.flat(Infinity); // [1, 2, 3, 4]
// flatMap() - map() then flat()
const nums = [1, 2, 3];
nums.flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
```
## fill()
```javascript
const arr = [1, 2, 3, 4];
arr.fill(0); // [0, 0, 0, 0]
arr.fill(0, 1, 3); // [1, 0, 0, 4] (start, end)
arr.fill(5, -2); // [1, 2, 5, 5] (from index -2 to end)
```
## copyWithin()
```javascript
const nums = [1, 2, 3, 4, 5];
nums.copyWithin(0, 3); // [4, 5, 3, 4, 5] (copy from index 3 to end, paste at 0)
nums.copyWithin(1, 2, 4); // [1, 3, 4, 4, 5] (copy positions 2-3, paste at 1)
```
## Array.isArray()
```javascript
Array.isArray([1, 2, 3]); // true
Array.isArray({}); // false
Array.isArray("hello"); // false
Array.isArray(new Array()); // true
```
## Chaining Methods
```javascript
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = nums
.filter(n => n % 2 === 0) // [2, 4, 6, 8, 10]
.map(n => n * 2) // [4, 8, 12, 16, 20]
.reduce((a, b) => a + b); // 60
```
## Summary
- Arrays are ordered collections that can hold any type of value
- `map()`, `filter()`, and `reduce()` are essential for functional programming
- Most array methods return new arrays, preserving immutability
- `forEach()` is for iteration side effects, not transformation
- Method chaining allows for expressive data transformations
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →