DevToolBoxZA DARMO
Blog

Metody Tablic JavaScript: kompletna sciagawka z przykladami

13 min czytaniaby DevToolBox

JavaScript Array Methods: The Complete Cheat Sheet

JavaScript arrays come with dozens of built-in methods that make data manipulation concise and expressive. Whether you are filtering, transforming, searching, or sorting data, there is a method for it. This comprehensive cheat sheet covers every commonly used array method with clear examples, return values, and use cases so you can write cleaner, more efficient JavaScript.

Creating Arrays

Before diving into methods, here are the common ways to create arrays in JavaScript:

// Array literal (most common)
const fruits = ["apple", "banana", "cherry"];

// Array constructor
const empty = new Array(3);       // [empty x 3]
const filled = new Array(1, 2, 3); // [1, 2, 3]

// Array.from — convert iterables and array-like objects
const chars = Array.from("hello");           // ["h", "e", "l", "l", "o"]
const range = Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4]

// Array.of — create from arguments (no special behavior for single number)
const single = Array.of(3); // [3] — not [empty x 3]

// Spread operator
const copy = [...fruits];
const merged = [...fruits, ...["date", "elderberry"]];

Transformation Methods (Return New Array)

These methods create and return a new array without modifying the original. They are the foundation of functional programming patterns in JavaScript.

map() - Transform Every Element

Creates a new array by applying a function to each element. The original array is not modified.

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]

const users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
];
const names = users.map(user => user.name);
// ["Alice", "Bob"]

// With index parameter
const indexed = numbers.map((n, i) => `${i}: ${n}`);
// ["0: 1", "1: 2", "2: 3", "3: 4", "4: 5"]

filter() - Select Matching Elements

Creates a new array with only the elements that pass a test function. Elements where the callback returns true are included.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evens = numbers.filter(n => n % 2 === 0);
// [2, 4, 6, 8, 10]

const adults = users.filter(user => user.age >= 18);

// Remove falsy values
const mixed = [0, "hello", "", null, 42, undefined, "world"];
const truthy = mixed.filter(Boolean);
// ["hello", 42, "world"]

// Remove duplicates (simple values)
const unique = numbers.filter((v, i, arr) => arr.indexOf(v) === i);

reduce() - Accumulate into Single Value

Reduces an array to a single value by applying a function against an accumulator and each element. This is the most versatile array method.

const numbers = [1, 2, 3, 4, 5];

// Sum
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15

// Max value
const max = numbers.reduce((a, b) => Math.max(a, b));
// 5

// Group by property
const people = [
  { name: "Alice", dept: "Engineering" },
  { name: "Bob", dept: "Marketing" },
  { name: "Carol", dept: "Engineering" },
];

const grouped = people.reduce((acc, person) => {
  const key = person.dept;
  acc[key] = acc[key] || [];
  acc[key].push(person);
  return acc;
}, {} as Record<string, typeof people>);
// { Engineering: [...], Marketing: [...] }

// Count occurrences
const words = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const counts = words.reduce((acc, word) => {
  acc[word] = (acc[word] || 0) + 1;
  return acc;
}, {} as Record<string, number>);
// { apple: 3, banana: 2, cherry: 1 }

// Flatten nested arrays (prefer flat() for simple cases)
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, arr) => [...acc, ...arr], [] as number[]);
// [1, 2, 3, 4, 5, 6]

flatMap() - Map Then Flatten

Combines map() and flat(1) in a single step. Useful when your mapping function returns arrays that should be flattened into the result.

const sentences = ["Hello world", "How are you"];

const words = sentences.flatMap(s => s.split(" "));
// ["Hello", "world", "How", "are", "you"]

// Filter and transform in one step
const nums = [1, 2, 3, 4, 5];
const evenDoubled = nums.flatMap(n => n % 2 === 0 ? [n * 2] : []);
// [4, 8]

flat() - Flatten Nested Arrays

const nested = [1, [2, 3], [4, [5, 6]]];

nested.flat();    // [1, 2, 3, 4, [5, 6]]  — depth 1
nested.flat(2);   // [1, 2, 3, 4, 5, 6]    — depth 2
nested.flat(Infinity); // flattens all levels

slice() - Extract a Portion

const arr = [1, 2, 3, 4, 5];

arr.slice(1, 3);   // [2, 3]     — from index 1 to 3 (exclusive)
arr.slice(2);      // [3, 4, 5]  — from index 2 to end
arr.slice(-2);     // [4, 5]     — last 2 elements
arr.slice();       // [1, 2, 3, 4, 5] — shallow copy

concat() - Merge Arrays

const a = [1, 2];
const b = [3, 4];
const c = [5, 6];

a.concat(b);        // [1, 2, 3, 4]
a.concat(b, c);     // [1, 2, 3, 4, 5, 6]
[...a, ...b, ...c]; // [1, 2, 3, 4, 5, 6] — spread alternative

Searching Methods

These methods help you find elements or check whether certain conditions are met within an array.

find() and findIndex()

const users = [
  { id: 1, name: "Alice", role: "admin" },
  { id: 2, name: "Bob", role: "user" },
  { id: 3, name: "Carol", role: "user" },
];

// find — returns first matching element or undefined
const admin = users.find(u => u.role === "admin");
// { id: 1, name: "Alice", role: "admin" }

// findIndex — returns index of first match or -1
const index = users.findIndex(u => u.name === "Bob");
// 1

// findLast and findLastIndex (ES2023)
const lastUser = users.findLast(u => u.role === "user");
// { id: 3, name: "Carol", role: "user" }

includes(), indexOf(), lastIndexOf()

const fruits = ["apple", "banana", "cherry", "banana"];

fruits.includes("banana");   // true
fruits.includes("grape");    // false

fruits.indexOf("banana");    // 1 (first occurrence)
fruits.lastIndexOf("banana"); // 3 (last occurrence)
fruits.indexOf("grape");     // -1 (not found)

some() and every()

const numbers = [1, 2, 3, 4, 5];

// some — at least one passes the test
numbers.some(n => n > 4);   // true
numbers.some(n => n > 10);  // false

// every — all must pass the test
numbers.every(n => n > 0);  // true
numbers.every(n => n > 3);  // false

// Practical: validate form fields
const fields = [
  { name: "email", value: "test@test.com", valid: true },
  { name: "name", value: "", valid: false },
];
const allValid = fields.every(f => f.valid); // false

Mutation Methods (Modify Original Array)

These methods change the original array in place. Use them when you intentionally want to modify the existing array rather than create a new one.

push(), pop(), unshift(), shift()

const arr = [1, 2, 3];

// Add to end — returns new length
arr.push(4);       // arr = [1, 2, 3, 4], returns 4
arr.push(5, 6);    // arr = [1, 2, 3, 4, 5, 6], returns 6

// Remove from end — returns removed element
arr.pop();         // arr = [1, 2, 3, 4, 5], returns 6

// Add to beginning — returns new length
arr.unshift(0);    // arr = [0, 1, 2, 3, 4, 5], returns 6

// Remove from beginning — returns removed element
arr.shift();       // arr = [1, 2, 3, 4, 5], returns 0

splice() - Add, Remove, or Replace

const arr = [1, 2, 3, 4, 5];

// Remove 2 elements starting at index 1
arr.splice(1, 2);  // returns [2, 3], arr = [1, 4, 5]

// Insert at index 1 without removing
arr.splice(1, 0, 2, 3); // arr = [1, 2, 3, 4, 5]

// Replace 1 element at index 2
arr.splice(2, 1, 99);   // returns [3], arr = [1, 2, 99, 4, 5]

sort() and reverse()

// sort modifies in place — returns the same array
const nums = [3, 1, 4, 1, 5, 9, 2, 6];

// Default sort converts to strings (careful with numbers!)
nums.sort();               // [1, 1, 2, 3, 4, 5, 6, 9]

// Numeric sort
nums.sort((a, b) => a - b); // ascending
nums.sort((a, b) => b - a); // descending

// Sort objects by property
const users = [
  { name: "Charlie", age: 35 },
  { name: "Alice", age: 28 },
  { name: "Bob", age: 32 },
];
users.sort((a, b) => a.age - b.age);
// Sorted by age ascending

// reverse — reverses in place
const arr = [1, 2, 3];
arr.reverse(); // [3, 2, 1]

// Non-mutating alternatives (ES2023)
const sorted = nums.toSorted((a, b) => a - b);
const reversed = arr.toReversed();
const spliced = arr.toSpliced(1, 1, 99);

fill() and copyWithin()

// fill — fill with a value
const arr = new Array(5).fill(0);  // [0, 0, 0, 0, 0]
arr.fill(7, 2, 4);                  // [0, 0, 7, 7, 0]

// copyWithin — copy part of array to another location
const arr2 = [1, 2, 3, 4, 5];
arr2.copyWithin(0, 3);  // [4, 5, 3, 4, 5] — copy from index 3 to index 0

Iteration Methods

const fruits = ["apple", "banana", "cherry"];

// forEach — execute for each element (returns undefined)
fruits.forEach((fruit, index) => {
  console.log(`${index}: ${fruit}`);
});

// for...of — modern loop with break/continue support
for (const fruit of fruits) {
  if (fruit === "banana") continue;
  console.log(fruit);
}

// entries(), keys(), values()
for (const [index, fruit] of fruits.entries()) {
  console.log(`${index}: ${fruit}`);
}

for (const key of fruits.keys()) {
  console.log(key); // 0, 1, 2
}

for (const value of fruits.values()) {
  console.log(value); // "apple", "banana", "cherry"
}

Conversion Methods

const arr = [1, 2, 3, 4, 5];

// join — convert to string with separator
arr.join(", ");  // "1, 2, 3, 4, 5"
arr.join("-");   // "1-2-3-4-5"
arr.join("");    // "12345"

// toString
arr.toString();  // "1,2,3,4,5"

// Array.isArray — check if value is an array
Array.isArray([1, 2, 3]);    // true
Array.isArray("hello");      // false
Array.isArray({ length: 3 }); // false

ES2023+ New Array Methods

Recent JavaScript versions added several non-mutating alternatives to existing mutation methods. These return new arrays instead of modifying the original.

const original = [3, 1, 4, 1, 5];

// toSorted — non-mutating sort
const sorted = original.toSorted((a, b) => a - b);
// sorted = [1, 1, 3, 4, 5], original unchanged

// toReversed — non-mutating reverse
const reversed = original.toReversed();
// reversed = [5, 1, 4, 1, 3], original unchanged

// toSpliced — non-mutating splice
const spliced = original.toSpliced(1, 2, 9, 8);
// spliced = [3, 9, 8, 1, 5], original unchanged

// with — non-mutating index assignment
const updated = original.with(2, 99);
// updated = [3, 1, 99, 1, 5], original unchanged

// Object.groupBy (ES2024) — group by callback result
const items = [
  { name: "Apple", type: "fruit" },
  { name: "Carrot", type: "vegetable" },
  { name: "Banana", type: "fruit" },
];

const groups = Object.groupBy(items, item => item.type);
// { fruit: [{...}, {...}], vegetable: [{...}] }

Quick Reference Table

MethodReturnsMutates?Use Case
map()New arrayNoTransform each element
filter()New arrayNoSelect matching elements
reduce()Any valueNoAccumulate to single value
find()Element or undefinedNoFirst match
findIndex()NumberNoIndex of first match
some()BooleanNoAt least one passes
every()BooleanNoAll pass
includes()BooleanNoContains value
flat()New arrayNoFlatten nested arrays
flatMap()New arrayNoMap then flatten
slice()New arrayNoExtract portion
concat()New arrayNoMerge arrays
sort()Same arrayYesSort in place
reverse()Same arrayYesReverse in place
push()New lengthYesAdd to end
pop()Removed elementYesRemove from end
splice()Removed elementsYesAdd/remove/replace
forEach()undefinedNoSide effects loop

Frequently Asked Questions

What is the difference between map() and forEach()?

map() returns a new array with the transformed values, while forEach() returnsundefined and is used only for side effects like logging or DOM manipulation. If you need the result, use map(). If you just need to do something with each element, use forEach().

When should I use reduce() vs a for loop?

Use reduce() when the operation naturally accumulates into a single value (sum, grouping, counting). Use a for loop when the logic is complex, involves multiple accumulators, or needs early termination. Readability should be the deciding factor.

How do I remove duplicates from an array?

For primitive values, use [...new Set(array)]. For objects, use filter() with aSet tracking seen keys, or use reduce() to build a map and extract values.

What is the performance of find() vs filter()?

find() stops at the first match and returns immediately, making it O(1) in the best case.filter() always iterates through the entire array. When you only need one result, always prefer find().

Are toSorted() and toReversed() supported in all browsers?

These ES2023 methods are supported in Chrome 110+, Firefox 115+, Safari 16+, and Node.js 20+. For older environments, use [...arr].sort() and [...arr].reverse() as non-mutating alternatives.

𝕏 Twitterin LinkedIn
Czy to było pomocne?

Bądź na bieżąco

Otrzymuj cotygodniowe porady i nowe narzędzia.

Bez spamu. Zrezygnuj kiedy chcesz.

Try These Related Tools

{ }JSON FormatterJSJavaScript Minifier

Related Articles

Ściągawka metod tablic JavaScript

Kompletna referencja metod tablic JavaScript: map, filter, reduce, find, some, every i więcej z przykładami.

Przykłady JavaScript map(), filter(), reduce()

Opanuj programowanie funkcyjne JavaScript z map, filter i reduce. Łańcuchowanie i transformacje danych.

JavaScript String Replace z Regex: replaceAll, grupy przechwytywania i przykłady

Opanuj zamianę stringów JavaScript z regex.