JavaScript Arrays & Array Methods
Master JavaScript arrays, their methods, and modern array manipulation techniques. This is a foundational concept in programming and web interactivity that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world JavaScript experience. Take your time with each section and practice the examples
Array Fundamentals
Arrays are ordered collections of values that can store any type of data. JavaScript provides a rich set of methods for manipulating arrays.. This is an essential concept that every JavaScript developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Array Creation & Basics
// Array creation methods
// 1. Array literal
const fruits = ["apple", "banana", "orange"];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, { name: "John" }];
// 2. Array constructor
const colors = new Array("red", "green", "blue");
const emptyArray = new Array(5); // Creates array with 5 empty slots
// 3. Array.from()
const arrayFromString = Array.from("hello"); // ["h", "e", "l", "l", "o"]
const arrayFromSet = Array.from(new Set([1, 2, 2, 3])); // [1, 2, 3]
// 4. Spread operator
const original = [1, 2, 3];
const copy = [...original]; // [1, 2, 3]
// Array access
console.log(fruits[0]); // "apple"
console.log(fruits[fruits.length - 1]); // "orange"
// Array length
console.log(fruits.length); // 3
// Array modification
fruits[1] = "grape"; // ["apple", "grape", "orange"]
fruits.push("mango"); // Add to end
fruits.unshift("kiwi"); // Add to beginning
fruits.pop(); // Remove from end
fruits.shift(); // Remove from beginning
console.log(fruits); // ["grape", "orange"]Array Methods
- map(): Transform each element
- filter(): Select elements based on condition
- reduce(): Accumulate values
- forEach(): Execute function for each element
- find() & findIndex(): Search for elements
- some() & every(): Test conditions
- includes() & indexOf(): Check existence
- slice() & splice(): Extract and modify
- sort() & reverse(): Order elements
- join() & split(): String conversion
Array Method Examples
// Array methods in action
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 1. map() - Transform elements
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
const users = [
{ name: "John", age: 25 },
{ name: "Jane", age: 30 },
{ name: "Bob", age: 35 }
];
const names = users.map(user => user.name);
console.log(names); // ["John", "Jane", "Bob"]
// 2. filter() - Select elements
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6, 8, 10]
const adults = users.filter(user => user.age >= 30);
console.log(adults); // [{ name: "Jane", age: 30 }, { name: "Bob", age: 35 }]
// 3. reduce() - Accumulate values
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 55
const totalAge = users.reduce((total, user) => total + user.age, 0);
console.log(totalAge); // 90
// 4. forEach() - Execute for each element
numbers.forEach((num, index) => {
console.log(`Number ${index + 1}: ${num}`);
});
// 5. find() & findIndex() - Search elements
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 2
const janeIndex = users.findIndex(user => user.name === "Jane");
console.log(janeIndex); // 1
// 6. some() & every() - Test conditions
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true
const allAdults = users.every(user => user.age >= 18);
console.log(allAdults); // true
// 7. includes() & indexOf() - Check existence
console.log(numbers.includes(5)); // true
console.log(numbers.indexOf(5)); // 4
console.log(numbers.indexOf(99)); // -1 (not found)
// 8. slice() & splice() - Extract and modify
const firstThree = numbers.slice(0, 3);
console.log(firstThree); // [1, 2, 3]
const numbersCopy = [...numbers];
numbersCopy.splice(2, 2, 99, 100); // Remove 2 elements starting at index 2, insert 99, 100
console.log(numbersCopy); // [1, 2, 99, 100, 5, 6, 7, 8, 9, 10]
// 9. sort() & reverse() - Order elements
const fruits = ["banana", "apple", "orange"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "orange"]
const scores = [85, 92, 78, 96, 88];
scores.sort((a, b) => b - a); // Sort in descending order
console.log(scores); // [96, 92, 88, 85, 78]
// 10. join() & split() - String conversion
const words = ["hello", "world", "javascript"];
const sentence = words.join(" ");
console.log(sentence); // "hello world javascript"
const text = "apple,banana,orange";
const fruitArray = text.split(",");
console.log(fruitArray); // ["apple", "banana", "orange"]Modern Array Features (ES6+)
// Modern array features
// 1. Destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
// 2. Array.from() with mapping
const squares = Array.from([1, 2, 3, 4], x => x * x);
console.log(squares); // [1, 4, 9, 16]
// 3. Array.of() - Creates array from arguments
const array1 = Array.of(1, 2, 3);
const array2 = Array.of(5); // [5] (not [,,,,,])
console.log(array1); // [1, 2, 3]
console.log(array2); // [5]
// 4. find() and findIndex()
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Bob" }
];
const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: "Jane" }
// 5. flat() and flatMap() - ES2019
const nested = [1, [2, 3], [4, [5, 6]]];
const flattened = nested.flat();
console.log(flattened); // [1, 2, 3, 4, [5, 6]]
const deeplyFlattened = nested.flat(2);
console.log(deeplyFlattened); // [1, 2, 3, 4, 5, 6]
// 6. Array methods with arrow functions
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(evens); // [2, 4]
console.log(sum); // 15
// 7. Array spread operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
// 8. Array rest parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15Practice Exercise: Arrays
// Exercise: Build a Todo List Application
// 1. Create Todo class
class Todo {
constructor(title, description = "", priority = "medium") {
this.id = Date.now() + Math.random();
this.title = title;
this.description = description;
this.priority = priority;
this.completed = false;
this.createdAt = new Date();
}
toggle() {
this.completed = !this.completed;
return this.completed;
}
update(updates) {
Object.assign(this, updates);
}
}
// 2. Create TodoList class
class TodoList {
constructor() {
this.todos = [];
}
addTodo(title, description, priority) {
const todo = new Todo(title, description, priority);
this.todos.push(todo);
return todo;
}
removeTodo(id) {
const index = this.todos.findIndex(todo => todo.id === id);
if (index !== -1) {
return this.todos.splice(index, 1)[0];
}
return null;
}
getTodo(id) {
return this.todos.find(todo => todo.id === id);
}
getAllTodos() {
return [...this.todos];
}
getCompletedTodos() {
return this.todos.filter(todo => todo.completed);
}
getPendingTodos() {
return this.todos.filter(todo => !todo.completed);
}
getTodosByPriority(priority) {
return this.todos.filter(todo => todo.priority === priority);
}
searchTodos(query) {
return this.todos.filter(todo =>
todo.title.toLowerCase().includes(query.toLowerCase()) ||
todo.description.toLowerCase().includes(query.toLowerCase())
);
}
getStats() {
const total = this.todos.length;
const completed = this.getCompletedTodos().length;
const pending = this.getPendingTodos().length;
return {
total,
completed,
pending,
completionRate: total > 0 ? (completed / total * 100).toFixed(1) : 0
};
}
}
// 3. Test the Todo List
const todoList = new TodoList();
todoList.addTodo("Learn JavaScript", "Complete the JavaScript course", "high");
todoList.addTodo("Buy groceries", "Milk, bread, eggs", "medium");
todoList.addTodo("Exercise", "30 minutes cardio", "low");
todoList.addTodo("Read book", "Finish the current novel", "medium");
console.log("All todos:", todoList.getAllTodos().length);
console.log("Pending todos:", todoList.getPendingTodos().length);
// Complete a todo
const firstTodo = todoList.getAllTodos()[0];
firstTodo.toggle();
console.log("Completed todos:", todoList.getCompletedTodos().length);
console.log("Stats:", todoList.getStats());
// Search todos
const searchResults = todoList.searchTodos("javascript");
console.log("Search results:", searchResults);
// Get todos by priority
const highPriority = todoList.getTodosByPriority("high");
console.log("High priority todos:", highPriority.length);