⚡ JavaScript

طرق المصفوفات والمجموعات في JavaScript (Node.js): دليل مفصل

Here is the translated HTML article in English:

What is it and why? (a real-life analogy)

Imagine you are a librarian. You have a huge bookshelf with books. Each book is a separate data element. Before, to find a book by author, you had to manually go through each book, write its title on a piece of paper, then look for the next one... It was slow and tedious.

Now imagine you have a magical robot assistant. You tell it: "Find all of Tolstoy's books and put them on the top shelf". The robot instantly scans the shelf, selects the right books, and completes the task. Array and collection methods in JavaScript are exactly these magical commands for your code.

An array is simply an ordered list of anything: numbers, strings, other arrays, or objects. Methods are built-in functions that can work with this list: add, remove, search, sort, transform elements.

💡 Important: Array methods do not change the original array (unless stated otherwise). They return a new result. It's like a photocopier: you make a copy of the list and work with it, while the original remains untouched.

Theory: how it works internally

Let's look under the hood of JavaScript. An array is a special type of object. It has numeric indices (0, 1, 2...) and a length property. When you call a method, the JavaScript engine (e.g., V8 in Node.js) iterates through the array elements in a loop and applies the given function to each one.

Let's consider the most popular method — forEach. It simply "runs through" each element and performs an action for it. Internally, it does something like this loop:

// Simplified internal implementation of forEach
function myForEach(array, callback) {
  for (let i = 0; i < array.length; i++) {
    // Call the callback function for each element
    callback(array[i], i, array);
  }
}

// Usage:
const numbers = [10, 20, 30];
myForEach(numbers, (item, index) => {
  console.log(`Element ${item} at position ${index}`);
});
// Output:
// Element 10 at position 0
// Element 20 at position 1
// Element 30 at position 2

Key concept: callback function. This is a function that you pass to the method. The method itself decides when to call it and with what arguments. Usually, the callback receives three arguments:

  • currentValue — the current element of the array
  • index — its index (position number)
  • array — the array itself (rarely needed)

Methods are divided into several groups:

  • Mutating — change the original array (e.g., push, pop, splice)
  • Non-mutating — return a new array (e.g., map, filter, slice)
  • Iterative — iterate through the array but return nothing (forEach)
  • Search — find an element or its index (find, indexOf)

Syntax in JavaScript (Node.js): all forms and variations

Let's look at the main methods with syntax examples. All examples work in Node.js version 18+.

1. Adding and removing elements

Method What it does Mutates? Returns
push(el1, el2, ...) Adds elements to the end ✅ Yes New array length
pop() Removes the last element ✅ Yes Removed element
unshift(el1, ...) Adds elements to the beginning ✅ Yes New length
shift() Removes the first element ✅ Yes Removed element
splice(start, deleteCount, item1, ...) Removes, replaces, or adds elements ✅ Yes Array of removed elements
// Examples with comments
const fruits = ['apple', 'banana'];

// push — add to the end
const newLength = fruits.push('orange', 'kiwi');
console.log(fruits); // ['apple', 'banana', 'orange', 'kiwi']
console.log(newLength); // 4 — method returned the new length

// pop — take the last one
const lastFruit = fruits.pop();
console.log(lastFruit); // 'kiwi'
console.log(fruits); // ['apple', 'banana', 'orange']

// unshift — add to the beginning
fruits.unshift('pear');
console.log(fruits); // ['pear', 'apple', 'banana', 'orange']

// shift — remove the first one
const firstFruit = fruits.shift();
console.log(firstFruit); // 'pear'

// splice — remove 1 element starting from index 1
const removed = fruits.splice(1, 1);
console.log(removed); // ['banana']
console.log(fruits); // ['pear', 'orange']

2. Transformation and filtering

Method What it does Returns
map(callback) Creates a new array by transforming each element New array of the same length
filter(callback) Creates a new array from elements that pass the test New array (may be shorter)
reduce(callback, initialValue) Reduces the array to a single value Single value (number, string, object)