Pages - Menu

Thursday, 11 July 2024

The differences and use cases for find, filter, map, reduce, and from in JavaScript

The differences and use cases for find, filter, map, reduce, and from in JavaScript:

find:
Purpose: Finds the first element in an array that satisfies a given condition. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const found = numbers.find(item => item === 3);
console.log(found); // 3
When to Use: When you need to locate a specific element based on a condition.

filter:
Purpose: Creates a new array with elements that pass a specified test. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]
When to Use: To filter out elements that don’t meet a certain condition.

map:
Purpose: Creates a new array by applying a function to each element in the original array. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
When to Use: When you want to transform each element in an array.

reduce:
Purpose: Reduces an array to a single value by applying a function to each element. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10
When to Use: For aggregating values (e.g., sum, product, concatenation).

from:
Purpose: Creates a new array from an iterable (e.g., string, Set, Map). Usage: JavaScript
const str = 'Hello';
const charArray = Array.from(str);
console.log(charArray); // ['H', 'e', 'l', 'l', 'o']
When to Use: When converting non-array iterables into arrays.

No comments:

Post a Comment