Working with Arrays
Working with Arrays
Arrays are ordered collections of data in JavaScript.
Creating Arrays
// Array literal
const fruits = ['apple', 'banana', 'orange'];// Array constructor
const numbers = new Array(1, 2, 3);
// Array.from()
const chars = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
Common Array Methods
Adding/Removing Elements
const arr = [1, 2, 3];arr.push(4); // [1, 2, 3, 4] - add to end
arr.pop(); // [1, 2, 3] - remove from end
arr.unshift(0); // [0, 1, 2, 3] - add to start
arr.shift(); // [1, 2, 3] - remove from start
Transforming Arrays
const numbers = [1, 2, 3, 4, 5];// map - transform each element
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]
// filter - keep elements that pass test
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]
// reduce - combine into single value
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15
Finding Elements
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];const user = users.find(u => u.id === 1);
// { id: 1, name: 'Alice' }
const index = users.findIndex(u => u.name === 'Bob');
// 1
Spread Operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
// [1, 2, 3, 4, 5, 6]