JavaScript
/Intermediate
Array Methods
Definition
Array methods are built-in functions in JavaScript that allow you to easily manipulate, search, and transform arrays without having to write manual loops.
Explain Like I'm New
Instead of using a bulky `for` loop every time you want to do something to a list of items, JavaScript gives you shortcuts. `map` is like putting every item through a machine to change it. `filter` is like a bouncer at a club who only lets certain items pass. `reduce` is like taking a pile of ingredients and combining them into a single cake.
Real World Example
If you have a list of user objects from a database, you might use `.filter()` to only show active users, and then use `.map()` to create a new list containing just their email addresses.
Common Use Cases
- •Transforming data structures for the UI
- •Filtering out bad data or deleted items
- •Calculating totals (like a shopping cart sum using reduce)
Terminal Output
bash / terminal
const numbers = [1, 2, 3, 4, 5];
// MAP: Transforms every item (creates new array)
const doubled = numbers.map(num => num * 2);
console.log('Doubled:', doubled); // [2, 4, 6, 8, 10]
// FILTER: Keeps items that pass a test (creates new array)
const evens = numbers.filter(num => num % 2 === 0);
console.log('Evens:', evens); // [2, 4]
// REDUCE: Accumulates all items into a single value
const sum = numbers.reduce((total, current) => total + current, 0);
console.log('Sum:', sum); // 15
// SPLICE: Mutates the original array
const months = ['Jan', 'March', 'April'];
months.splice(1, 0, 'Feb'); // Insert at index 1
console.log('Spliced:', months); // ['Jan', 'Feb', 'March', 'April']
Interview Questions
basic
- What is the difference between push() and unshift()?
- What does the map() method do?
intermediate
- What is the difference between slice() and splice()?
- How do map(), filter(), and reduce() differ?
advanced
- Does the sort() method mutate the original array? How does it sort by default?
- What is the difference between forEach() and map()?
trick
- How do you flatten a multi-dimensional array using flatMap()?