JavaScript arrays are incredibly versatile, and mastering their methods can make your code cleaner, faster, and more readable. This article highlights 10 essential array methods every developer should know, complete with examples to help you understand their power and applications.
1. map()
– Transforming Data
The map()
method creates a new array by applying a callback function to each element of the original array.
Example:
const numbers = [1, 2, 3, 4];
const squared = numbers.map(num => num ** 2);
console.log(squared); // [1, 4, 9, 16]
2. filter()
– Selecting Elements
The filter()
method returns a new array with elements that satisfy a given condition.
Example:
const ages = [15, 18, 21, 25];
const adults = ages.filter(age => age >= 18);
console.log(adults); // [18, 21, 25]
3. reduce()
– Summarizing Data
The reduce()
method applies a function to each element to reduce the array to a single value.
Example:
const prices = [10, 20, 30];
const total…