Array Methods

basic
Published

May 22, 2024

JavaScript arrays come with a rich set of built-in methods for manipulation, iteration, and transformation. This guide covers the most important array methods with practical examples.

Basic Array Manipulation

1. Adding and Removing Elements

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

// Adding elements
fruits.push('orange');              // Add to end
fruits.unshift('grape');            // Add to beginning
fruits.splice(2, 0, 'mango');       // Add at specific position

// Removing elements
const lastFruit = fruits.pop();     // Remove from end
const firstFruit = fruits.shift();  // Remove from beginning
fruits.splice(1, 1);                // Remove at specific position

// Examples
const numbers = [1, 2, 3];
numbers.push(4, 5);         // [1, 2, 3, 4, 5]
numbers.unshift(0);         // [0, 1, 2, 3, 4, 5]
numbers.pop();              // [0, 1, 2, 3, 4]
numbers.shift();            // [1, 2, 3, 4]
numbers.splice(1, 2);       // [1, 4]

2. Combining Arrays

const array1 = [1, 2];
const array2 = [3, 4];

// Concatenation
const combined = array1.concat(array2);        // [1, 2, 3, 4]
const spreadCombined = [...array1, ...array2]; // [1, 2, 3, 4]

// Joining elements
const letters = ['a', 'b', 'c'];
console.log(letters.join('-'));  // "a-b-c"

// Slicing
const numbers = [1, 2, 3, 4, 5];
const slice = numbers.slice(1, 3);  // [2, 3]

Iterative Methods

1. forEach

const numbers = [1, 2, 3];
numbers.forEach((num, index) => {
    console.log(`Number at index ${index}: ${num}`);
});

// Practical example
const items = [
    { id: 1, name: 'Book', price: 20 },
    { id: 2, name: 'Pen', price: 5 },
    { id: 3, name: 'Notebook', price: 10 }
];

let total = 0;
items.forEach(item => {
    total += item.price;
});

2. map

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

// Practical example
const users = [
    { id: 1, name: 'John', age: 30 },
    { id: 2, name: 'Jane', age: 25 }
];

const userNames = users.map(user => user.name);  // ['John', 'Jane']

// Chaining with other methods
const prices = [10.99, 5.99, 3.99, 6.59];
const formattedPrices = prices
    .map(price => price * 1.2)  // Add 20% tax
    .map(price => price.toFixed(2))  // Format to 2 decimal places
    .map(price => `$${price}`);      // Add dollar sign

3. filter

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

// Practical example
const products = [
    { id: 1, name: 'Laptop', price: 999, inStock: true },
    { id: 2, name: 'Phone', price: 599, inStock: false },
    { id: 3, name: 'Tablet', price: 399, inStock: true }
];

const availableProducts = products
    .filter(product => product.inStock)
    .filter(product => product.price < 500);

4. reduce

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);  // 10

// Practical examples
// Calculate total price
const cart = [
    { id: 1, price: 29.99, quantity: 2 },
    { id: 2, price: 9.99, quantity: 3 },
    { id: 3, price: 15.99, quantity: 1 }
];

const total = cart.reduce((acc, item) => {
    return acc + (item.price * item.quantity);
}, 0);

// Group objects by property
const people = [
    { age: 25, city: 'New York' },
    { age: 30, city: 'London' },
    { age: 25, city: 'Paris' }
];

const groupedByAge = people.reduce((acc, person) => {
    const age = person.age;
    if (!acc[age]) {
        acc[age] = [];
    }
    acc[age].push(person);
    return acc;
}, {});

Search and Sort Methods

1. find and findIndex

const numbers = [1, 2, 3, 4, 5];
const found = numbers.find(num => num > 3);       // 4
const index = numbers.findIndex(num => num > 3);  // 3

// Practical example
const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Bob' }
];

const user = users.find(user => user.id === 2);
const userIndex = users.findIndex(user => user.name === 'Bob');

2. includes and indexOf

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('banana'));     // true
console.log(fruits.indexOf('orange'));      // 2
console.log(fruits.lastIndexOf('apple'));   // 0

// Practical example
function validateFruit(fruit) {
    const validFruits = ['apple', 'banana', 'orange', 'grape'];
    return validFruits.includes(fruit.toLowerCase());
}

3. sort

// Basic sorting
const fruits = ['orange', 'apple', 'banana'];
fruits.sort();  // ['apple', 'banana', 'orange']

// Numeric sorting
const numbers = [10, 2, 5, 1, 9];
numbers.sort((a, b) => a - b);  // Ascending: [1, 2, 5, 9, 10]
numbers.sort((a, b) => b - a);  // Descending: [10, 9, 5, 2, 1]

// Complex object sorting
const products = [
    { name: 'Laptop', price: 999 },
    { name: 'Phone', price: 599 },
    { name: 'Tablet', price: 399 }
];

products.sort((a, b) => a.price - b.price);  // Sort by price
products.sort((a, b) => a.name.localeCompare(b.name));  // Sort by name

Modern Array Methods

1. flatMap and flat

// flat
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat());     // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2));    // [1, 2, 3, 4, 5, 6]

// flatMap
const sentences = ['Hello world', 'How are you'];
const words = sentences.flatMap(sentence => sentence.split(' '));
// ['Hello', 'world', 'How', 'are', 'you']

// Practical example
const orders = [
    { id: 1, items: ['book', 'pen'] },
    { id: 2, items: ['notebook'] },
    { id: 3, items: ['pencil', 'eraser', 'ruler'] }
];

const allItems = orders.flatMap(order => order.items);

2. Array.from and Array.of

// 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]

// With mapping function
const numbers = Array.from({ length: 5 }, (_, i) => i + 1);  // [1, 2, 3, 4, 5]

// Array.of
const numbers = Array.of(1);        // [1]
const mixed = Array.of(1, 'two', { three: 3 });  // [1, 'two', { three: 3 }]

Best Practices and Tips

  1. Choose the Right Method
    • Use map when transforming every element
    • Use filter when selecting elements based on criteria
    • Use reduce for accumulating values or complex transformations
    • Use forEach when you just need to iterate
  2. Method Chaining
const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers
    .filter(n => n % 2 === 0)    // Get even numbers
    .map(n => n * 2)             // Double them
    .reduce((acc, n) => acc + n); // Sum them up
  1. Performance Considerations
    • Prefer for...of loops for simple iterations
    • Use map/filter when you need a new array
    • Consider using reduce for complex operations
    • Be mindful of creating too many intermediate arrays
  2. Immutability
// Bad: Modifying original array
const numbers = [1, 2, 3];
numbers.push(4);

// Good: Creating new array
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4];

JavaScript array methods provide powerful tools for data manipulation and transformation. Understanding these methods and their appropriate use cases is crucial for writing clean and efficient JavaScript code. The examples provided in this guide demonstrate various practical applications that you can adapt for your own projects.