Home > Web Front-end > JS Tutorial > ssential JavaScript Array Methods

ssential JavaScript Array Methods

Mary-Kate Olsen
Release: 2024-11-08 20:14:02
Original
471 people have browsed it

ssential 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]
Copy after login

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]
Copy after login

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

Copy after login

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

const firstEven = [1, 2, 3, 4, 5].find(num => num % 2 === 0); // 2
Copy after login

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

Copy after login

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]
Copy after login

Removing Duplicates: Using Set removes duplicates.

const uniqueNumbers = [...new Set([1, 2, 2, 3, 4, 4, 5])]; // [1, 2, 3, 4, 5]
Copy after login

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]
Copy after login

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

The above is the detailed content of ssential JavaScript Array Methods. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template