📝
JavaScript•9 dk okuma•20 Ocak 2024

Mastering JavaScript Array Methods

Master the essential JavaScript array methods like map, filter, reduce, and more. Learn with examples and best practices.

TR

TheRedGeek

Teknoloji Yazarı

#JavaScript#Array#Frontend#Functional Programming

Mastering JavaScript Array Methods

JavaScript arrays are a core part of the language and mastering their built-in methods is essential for efficient and clean code. In this article, we'll explore the most commonly used array methods with real-world examples, performance tips, and best practices.

🔄 Iteration Methods

forEach() – Loop through each item

const fruits = ['apple', 'banana', 'cherry']
fruits.forEach((fruit) => console.log(fruit))

map() – Transform each item

const prices = [10, 20, 30]
const taxIncluded = prices.map(price => price * 1.2)

filter() – Return items that match a condition

const scores = [40, 90, 85, 50]
const passed = scores.filter(score => score >= 60)

reduce() – Calculate a single value from an array

const numbers = [1, 2, 3, 4]
const sum = numbers.reduce((acc, num) => acc + num, 0)

find() – Return the first matching item

const users = [{ id: 1 }, { id: 2 }, { id: 3 }]
const user = users.find(user => user.id === 2)

✨ Useful Transformations

flat() – Flatten nested arrays

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

flatMap() – Combine map + flat

const arr = [1, 2, 3]
const result = arr.flatMap(n => [n, n * 2]) // [1, 2, 2, 4, 3, 6]

slice() vs splice()

const items = ['a', 'b', 'c', 'd']
const part = items.slice(1, 3) // ['b', 'c']

items.splice(1, 2) // ['b', 'c'] removed // items is now ['a', 'd']

🔎 Searching & Checking

includes() – Check if array contains a value

const tags = ['react', 'vue', 'angular']
tags.includes('vue') // true

some() – At least one item matches

const numbers = [1, 3, 5, 8]
numbers.some(n => n % 2 === 0) // true

every() – All items match

const valid = [18, 22, 25]
valid.every(age => age >= 18) // true

đź§Ş Sorting & Reordering

sort() – Sort alphabetically or numerically

const names = ['Charlie', 'Alice', 'Bob']
names.sort() // ['Alice', 'Bob', 'Charlie']

const nums = [10, 1, 20] nums.sort((a, b) => a - b) // [1, 10, 20]

reverse() – Reverse the order

const letters = ['a', 'b', 'c']
letters.reverse() // ['c', 'b', 'a']

join() – Combine elements into a string

const words = ['JavaScript', 'is', 'awesome']
const sentence = words.join(' ') // "JavaScript is awesome"

📌 Performance Tips

  • map, filter, and reduce are non-mutating – they return a new array.
  • splice, sort, and reverse mutate the original array.
  • Avoid chaining too many transformations in performance-critical code.
  • Use Set or Map for faster lookups when necessary.
  • âś… Best Practices

    1. Immutability: Prefer pure methods that return new arrays. 2. Readability: Name callback parameters clearly. 3. Avoid complex nesting: Break complex reduce() chains into separate steps. 4. Debug step-by-step: Use console.log() inside callbacks to trace transformations.

    🔍 Real-World Example: Filtering & Grouping

    const tasks = [
      { id: 1, done: true },
      { id: 2, done: false },
      { id: 3, done: true },
    ]

    const doneTasks = tasks.filter(task => task.done) const pending = tasks.filter(task => !task.done)

    📚 Conclusion

    JavaScript Array methods are powerful tools that can transform and manipulate data efficiently. Whether you're filtering, mapping, sorting, or reducing, knowing the right method—and when to use it—can make your code cleaner and faster.

    Bu Yazıyı Paylaş

    Daha Fazla İçerik İçin Abone Olun

    En yeni teknoloji yazılarımızdan haberdar olmak için bültenimize abone olun.