Javascript Functional Array Methods


JavaScript Functional Array Methods: A Quick Guide

JavaScript provides powerful functional methods for working with arrays. These methods make it easy to filter, transform, and manipulate data efficiently. Let’s explore some key methods.

1. every() – Check If All Elements Match a Condition

Checks if all elements in an array pass a test.

const numbers = [2, 4, 6, 8];
const allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // true

2. some() – Check If Any Element Matches a Condition

Returns true if at least one element meets the condition.

const numbers = [3, 7, 8, 9];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true (8 is even)

3. filter() – Create a New Array with Matching Elements

Filters elements based on a condition and returns a new array.

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

4. map() – Transform Elements into a New Array

Applies a function to each element and returns a new array.

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

5. reduce() – Accumulate Values into a Single Result

Reduces an array to a single value (e.g., sum, product).

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

6. find() – Get the First Matching Element

Returns the first element that meets the condition.

const numbers = [5, 12, 8, 130, 44];
const firstLarge = numbers.find(num => num > 10);
console.log(firstLarge); // 12

7. findIndex() – Get the Index of the First Matching Element

Returns the index of the first matching element.

const numbers = [5, 12, 8, 130, 44];
const index = numbers.findIndex(num => num > 10);
console.log(index); // 1 (index of 12)

8. forEach() – Iterate Over Each Element

Executes a function on each array element (no return value).

const numbers = [1, 2, 3];
numbers.forEach(num => console.log(num * 2));
// Output: 2, 4, 6

Summary

MethodPurpose
every()Checks if all elements pass a test
some()Checks if at least one element passes a test
filter()Returns new array with matching elements
map()Returns new array with modified elements
reduce()Returns a single value from elements
find()Returns first matching element
findIndex()Returns index of first matching element
forEach()Iterates over array but doesn’t return a new one

By mastering these methods, you can write cleaner and more efficient JavaScript code. Happy coding! 🚀