DEV Community

Midhul P
Midhul P

Posted on

1

8 Essential JavaScript Array Methods

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more