JavaScript arrays come with powerful one-liners that make coding simpler and cleaner. Here’s a quick guide to mastering some key array methods:
Filtering an Array: .filter() creates a new array with elements passing a test.
const oddNumbers = [1, 2, 3, 4, 5, 6].filter(num => num % 2 !== 0); // [1, 3, 5]
Mapping an Array: .map() applies a function to every element.
const doubled = [1, 2, 3, 4, 5].map(num => num * 2); // [2, 4, 6, 8, 10]
Reducing an Array: .reduce() processes all elements to produce a single result.
const sum = [1, 2, 3, 4, 5].reduce((total, num) => total + num, 0); // 15
*Finding an Element: *.find() returns the first element meeting a condition.
const firstEven = [1, 2, 3, 4, 5].find(num => num % 2 === 0); // 2
Checking Conditions: .some() and .every() check if any or all elements pass a test.
const hasEven = [1, 3, 5, 7, 8].some(num => num % 2 === 0); // true
Flattening an Array: .flat() turns nested arrays into a single-level array.
const flattened = [1, [2, 3], [4, [5, 6]]].flat(2); // [1, 2, 3, 4, 5, 6]
Removing Duplicates: Using Set removes duplicates.
const uniqueNumbers = [...new Set([1, 2, 2, 3, 4, 4, 5])]; // [1, 2, 3, 4, 5]
Sorting an Array: .sort() arranges numbers.
const sortedNumbers = [5, 2, 9, 1, 5, 6].sort((a, b) => a - b); // [1, 2, 5, 5, 6, 9]
These one-liners can significantly streamline your code. To dive deeper, check out my JavaScript cheatsheet and more