8 Essential JavaScript Array Methods

Midhul P - Nov 8 - - Dev Community

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

*Finding an Element: *.find() returns the first element meeting a condition.

const firstEven = [1, 2, 3, 4, 5].find(num => num % 2 === 0); // 2
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Removing Duplicates: Using Set removes duplicates.

const uniqueNumbers = [...new Set([1, 2, 2, 3, 4, 4, 5])]; // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

These one-liners can significantly streamline your code. To dive deeper, check out my JavaScript cheatsheet and more

. . . . .