Arrays

List-like objects and common methods

JavaScript Arrays

Arrays are ordered lists that can store any type of value. They're one of the most commonly used data structures in JavaScript.

Creating Arrays

// Array literal (most common)
const fruits = ["apple", "banana", "orange"];

// Array constructor
const numbers = new Array(1, 2, 3, 4, 5);

// Mixed types (possible but not recommended)
const mixed = [1, "text", true, null, { id: 1 }];

// Empty array
const empty = [];

Accessing Elements

const fruits = ["apple", "banana", "orange"];

// By index (zero-based)
console.log(fruits[0]);  // "apple"
console.log(fruits[1]);  // "banana"

// Get length
console.log(fruits.length);  // 3

// Last element
console.log(fruits[fruits.length - 1]);  // "orange"

// Using at() method (modern)
console.log(fruits.at(-1));  // "orange" (negative indices work!)

Adding & Removing Elements

const fruits = ["apple", "banana"];

// Add to end
fruits.push("orange");  // ["apple", "banana", "orange"]

// Remove from end
const last = fruits.pop();  // "orange", fruits is now ["apple", "banana"]

// Add to beginning
fruits.unshift("mango");  // ["mango", "apple", "banana"]

// Remove from beginning
const first = fruits.shift();  // "mango", fruits is now ["apple", "banana"]

// Remove/add at specific index
fruits.splice(1, 0, "grape");  // Add "grape" at index 1
// ["apple", "grape", "banana"]

fruits.splice(1, 1);  // Remove 1 element at index 1
// ["apple", "banana"]

Essential Array Methods

.map() - Transform Each Element

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
// [2, 4, 6, 8, 10]

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 }
];
const names = users.map(user => user.name);
// ["Alice", "Bob"]

.filter() - Keep Elements That Match

const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(num => num % 2 === 0);
// [2, 4, 6]

const users = [
  { name: "Alice", age: 17 },
  { name: "Bob", age: 25 }
];
const adults = users.filter(user => user.age >= 18);
// [{ name: "Bob", age: 25 }]

.reduce() - Combine Into Single Value

const numbers = [1, 2, 3, 4, 5];

// Sum all numbers
const sum = numbers.reduce((total, num) => total + num, 0);
// 15

// Find max
const max = numbers.reduce((max, num) => num > max ? num : max);
// 5

// Group by property
const people = [
  { name: "Alice", role: "dev" },
  { name: "Bob", role: "designer" },
  { name: "Charlie", role: "dev" }
];

const byRole = people.reduce((acc, person) => {
  if (!acc[person.role]) acc[person.role] = [];
  acc[person.role].push(person);
  return acc;
}, {});
// { dev: [...], designer: [...] }

.find() & .findIndex()

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" }
];

// Find first match
const user = users.find(u => u.id === 2);
// { id: 2, name: "Bob" }

// Find index of first match
const index = users.findIndex(u => u.id === 2);
// 1

Other Useful Methods

const fruits = ["apple", "banana", "orange"];

// Check if element exists
fruits.includes("banana");  // true
fruits.indexOf("banana");   // 1 (or -1 if not found)

// Check if any/all match condition
const numbers = [1, 2, 3, 4, 5];
numbers.some(num => num > 4);   // true (at least one is > 4)
numbers.every(num => num > 0);  // true (all are > 0)

// Join into string
fruits.join(", ");  // "apple, banana, orange"

// Slice (extract portion)
const slice = fruits.slice(1, 3);  // ["banana", "orange"]

// Reverse
const reversed = fruits.reverse();  // ["orange", "banana", "apple"]

// Sort
const nums = [3, 1, 4, 1, 5];
nums.sort((a, b) => a - b);  // [1, 1, 3, 4, 5]

Method Chaining

Combine multiple array methods:

const users = [
  { name: "Alice", age: 17, score: 85 },
  { name: "Bob", age: 25, score: 92 },
  { name: "Charlie", age: 30, score: 78 },
  { name: "Diana", age: 22, score: 95 }
];

// Get names of adults with score > 80
const result = users
  .filter(user => user.age >= 18)     // Filter adults
  .filter(user => user.score > 80)    // Filter high scorers
  .map(user => user.name)             // Get names
  .sort();                             // Sort alphabetically

console.log(result);  // ["Bob", "Diana"]

⚠️ Watch Out For

  • .sort() mutates the original array
  • .reverse() mutates the original array
  • • Always provide a compare function to .sort() for numbers
  • .map(), .filter(), .slice() return new arrays (don't mutate)

✓ Best Practices

  • • Prefer .map(), .filter(), .reduce() over for loops
  • • Use .find() instead of .filter()[0]
  • • Use .includes() for checking existence
  • • Chain methods for readable data transformations
  • • Be aware of methods that mutate vs return new arrays