Skip to content

Archive

Array

21 articles
Rust Updated 02 Sep 2025 3 min read

Working with Arrays in Rust

An array in Rust is a fixed-size collection whose elements all have the same type. Arrays are useful when the number of elements is known at compile time and should not grow or shrink during execution. What Is an Array in Rust? The type of an array includes both its element type and its length. For example, [i32; 5] is an array containing exactly five i32 values. A differently sized array is a different type.

JavaScript Updated 02 Sep 2025 3 min read

Understanding Watchers in Vue 3

Vue 3 watchers let you run side-effect logic when reactive data changes. They are useful for tasks such as triggering an API request, synchronizing with an external system, persisting state, or responding to a transition between values. 1. What Is a Watcher? A watcher observes one or more reactive sources and runs a callback when their values change. Unlike a computed property, which represents derived state, a watcher is usually intended for side effects.

JavaScript Updated 02 Sep 2025 1 min read

Handle Multiple Promises with `Promise.allSettled()`

Promise.allSettled() waits until every input promise has either fulfilled or rejected, then returns the outcome of each operation. Unlike Promise.all(), one rejection does not stop you from receiving the other results. const tasks = [ Promise.resolve('first result'), Promise.reject(new Error('second failed')), Promise.resolve('third result'), ]; const results = await Promise.allSettled(tasks); for (const result of results) { if (result.status === 'fulfilled') { console.log('Value:', result.value); } else { console.error('Error:', result.reason); } } Each result has one of these shapes:

JavaScript Updated 02 Sep 2025 1 min read

Get Every RegExp Match with `String.matchAll()`

String.prototype.matchAll() returns an iterator containing every match of a global regular expression, including capturing groups and match indexes. const text = 'Order #123, Order #456, Order #789'; const regex = /Order #(\d+)/g; for (const match of text.matchAll(regex)) { console.log(match[0], match[1], match.index); } Named Capturing Groups const text = 'John: 123, Jane: 456'; const regex = /(?<name>\w+): (?<number>\d+)/g; for (const match of text.matchAll(regex)) { console.log(match.groups.name, match.groups.number); } Convert the Iterator to an Array const matches = [...'cat bat mat'.matchAll(/\b(\w+)at\b/g)]; This is convenient when you need map, filter, or other array operations, but iterating directly avoids storing all matches at once.

JavaScript Updated 02 Sep 2025 1 min read

Access JavaScript Array Elements with `at()`

Array.prototype.at() returns the element at a given integer index. Its main advantage over bracket notation is support for negative indexes. Positive Indexes const fruits = ['apple', 'banana', 'cherry']; console.log(fruits.at(0)); // 'apple' console.log(fruits.at(1)); // 'banana' Negative Indexes console.log(fruits.at(-1)); // 'cherry' console.log(fruits.at(-2)); // 'banana' Without at(), the traditional equivalent for the last element is:

JavaScript Updated 07 Sep 2025 1 min read

Update JavaScript Arrays Immutably with `with()`

Array.prototype.with() returns a copy of an array with one element replaced. The source array is left unchanged. const colors = ['red', 'blue', 'green', 'yellow']; const updated = colors.with(1, 'purple'); console.log(updated); // ['red', 'purple', 'green', 'yellow'] console.log(colors); // ['red', 'blue', 'green', 'yellow'] Negative Indexes Like at(), with() accepts negative indexes:

JavaScript Updated 02 Sep 2025 1 min read

Understanding `for`, `forEach`, and `map` in JavaScript

JavaScript offers several ways to iterate over arrays. for, forEach, and map overlap in what they can express, but each communicates a different intent. Traditional for const numbers = [1, 2, 3, 4, 5]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } Use a for loop when you need explicit index control, break, continue, unusual step sizes, or tight control over the iteration process.

JavaScript Updated 07 Sep 2025 2 min read

Sort JavaScript Arrays Immutably with `toSorted()`

toSorted() returns a sorted copy of an array without modifying the original. It is the non-mutating counterpart to sort(). Basic Usage For numbers, provide a comparator because the default sort order is based on strings: const numbers = [5, 3, 8, 1]; const sortedNumbers = numbers.toSorted((a, b) => a - b); console.log(sortedNumbers); // [1, 3, 5, 8] console.log(numbers); // [5, 3, 8, 1] Sort Objects const students = [ { name: 'Alice', grade: 85 }, { name: 'Bob', grade: 92 }, { name: 'Charlie', grade: 88 }, ]; const sortedByGrade = students.toSorted((a, b) => b.grade - a.grade); console.log(sortedByGrade); console.log(students); // unchanged Sort Strings with a Custom Rule const words = ['banana', 'apple', 'cherry']; const sortedWords = words.toSorted((a, b) => a.length - b.length); For locale-aware alphabetical ordering, use localeCompare:

JavaScript Updated 02 Sep 2025 1 min read

Reverse JavaScript Arrays Immutably with `toReversed()`

toReversed() returns a new array with the elements in reverse order while leaving the original array unchanged. It is the non-mutating counterpart to reverse(). Basic Usage const originalArray = [1, 2, 3, 4, 5]; const reversedArray = originalArray.toReversed(); console.log(reversedArray); // [5, 4, 3, 2, 1] console.log(originalArray); // [1, 2, 3, 4, 5] toReversed() vs. reverse() const a = [1, 2, 3]; const b = a.reverse(); console.log(a); // [3, 2, 1] console.log(b === a); // true reverse() changes the existing array. By contrast:

JavaScript Updated 07 Sep 2025 1 min read

Modify JavaScript Arrays Immutably with `toSpliced()`

toSpliced() creates a modified copy of an array without changing the source array. It is the non-mutating counterpart to splice(). Syntax array.toSpliced(start, deleteCount, ...items) start is the index where the change begins. deleteCount controls how many existing elements are removed. items are inserted at that position. Replace Elements const fruits = ['apple', 'banana', 'cherry', 'date']; const updated = fruits.toSpliced(1, 2, 'blueberry', 'fig'); console.log(updated); // ['apple', 'blueberry', 'fig', 'date'] console.log(fruits); // unchanged Insert Without Deleting const numbers = [1, 2, 5]; const result = numbers.toSpliced(2, 0, 3, 4); console.log(result); // [1, 2, 3, 4, 5] Remove Elements const values = ['a', 'b', 'c', 'd']; const result = values.toSpliced(1, 2); console.log(result); // ['a', 'd'] Why It Is Useful Non-mutating updates are especially helpful in UI state management, reducers, and code where several consumers share the same array reference. toSpliced() makes that intent explicit without manually combining slices.

JavaScript Updated 02 Sep 2025 1 min read

Group JavaScript Data with `Object.groupBy()`

Object.groupBy() groups iterable values by a key returned from a callback and produces an object whose properties contain arrays of matching items. Group Numbers const numbers = [1, 2, 3, 4, 5, 6]; const grouped = Object.groupBy(numbers, (number) => number % 2 === 0 ? 'even' : 'odd' ); The result has even and odd arrays.

JavaScript Updated 02 Sep 2025 2 min read

Group Data with JavaScript `Map.groupBy()`

Map.groupBy() groups iterable values into a Map. The callback determines the key for each group, and every map value is an array of matching elements. Basic Example const numbers = [1, 2, 3, 4, 5, 6]; const grouped = Map.groupBy(numbers, (number) => number % 2 === 0 ? 'even' : 'odd' ); console.log(grouped.get('even')); // [2, 4, 6] Group Objects const products = [ { name: 'Laptop', category: 'Electronics' }, { name: 'Shirt', category: 'Clothing' }, { name: 'Phone', category: 'Electronics' }, ]; const grouped = Map.groupBy(products, (product) => product.category); Arbitrary Map Keys The main advantage over Object.groupBy() is that map keys can be objects and other values without being converted to property keys:

JavaScript Updated 02 Sep 2025 1 min read

Find the Last Matching Array Index with `findLastIndex()`

Array.prototype.findLastIndex() searches from the end of an array and returns the index of the first element, in reverse order, that matches a predicate. const numbers = [1, 3, 5, 8, 10, 12, 7, 6]; const index = numbers.findLastIndex((number) => number % 2 === 0); console.log(index); // 7 For object arrays:

JavaScript Updated 02 Sep 2025 1 min read

Find the Last Matching Array Element with `findLast()`

Array.prototype.findLast() searches an array from the end and returns the first element, in reverse order, that satisfies a predicate. const numbers = [1, 3, 5, 8, 10, 12, 7, 6]; const lastEven = numbers.findLast((number) => number % 2 === 0); console.log(lastEven); // 6 For objects:

Go Updated 02 Sep 2025 2 min read

Loops in Go: A Practical Guide with Examples

Go has only one looping keyword: for. That can look unusual if you come from a language with separate for, while, and do-while constructs, but Go’s for is flexible enough to cover the common looping patterns. 1. Basic for Loop for i := 0; i < 5; i++ { fmt.Println(i) } This is similar to a traditional loop in C, Java, or JavaScript: initialize a counter, continue while the condition is true, and run the post statement after each iteration.

Go Updated 02 Sep 2025 3 min read

Arrays and Slices in Go: Add, Delete, Search, Update, Sort, and Filter

Go arrays and slices are straightforward once you understand their different roles. Arrays have a fixed length that is part of their type, while slices are flexible views over an underlying array and are the collection type used most often in application code. The following examples use a slice of structs: type Person struct { Name string Age int } people := []Person{ {Name: "Alice", Age: 30}, {Name: "Bob", Age: 25}, {Name: "John", Age: 20}, {Name: "Zara", Age: 35}, } 1. Add an Element Use append:

Python Updated 02 Sep 2025 2 min read

Arrays in Python: Lists, `array`, and NumPy

Python has several ways to represent sequence data. The right choice depends on whether you need flexible general-purpose containers, compact typed storage, or high-performance numerical operations. 1. Lists: The Default General-Purpose Sequence Python lists are flexible and can contain objects of different types: numbers = [1, 2, 3, 4, 5] mixed = [1, "Python", 3.14, True] print(numbers[0]) numbers[1] = 10 numbers.append(6) For most application code, a list is the correct default.

JavaScript Updated 02 Sep 2025 2 min read

Split a JavaScript Array into Chunks

JavaScript does not have a built-in chunk method for splitting an array into equally sized groups, but the operation is easy to implement with slice. Chunking is useful for UI grids, pagination helpers, batching API operations, and processing large collections in smaller units. A Simple chunk Function function chunk(array, size) { if (!Number.isInteger(size) || size <= 0) { throw new RangeError('size must be a positive integer'); } const result = []; for (let i = 0; i < array.length; i += size) { result.push(array.slice(i, i + size)); } return result; } Use it like this:

JavaScript Updated 02 Sep 2025 2 min read

Remove Duplicates from JavaScript Arrays

Removing duplicates depends on what “duplicate” means for your data. Primitive values, objects with unique IDs, and records compared by several properties need different strategies. Primitive Values with Set const values = [1, 2, 3, 2, 4, 3]; const unique = [...new Set(values)]; console.log(unique); // [1, 2, 3, 4] Keep the First Object for Each ID const items = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice again' }, ]; const seen = new Set(); const unique = items.filter((item) => { if (seen.has(item.id)) return false; seen.add(item.id); return true; }); Keep the Last Object for Each ID A Map naturally overwrites earlier values for the same key:

JavaScript Updated 07 Sep 2025 1 min read

Sort JavaScript Object Arrays by a Property Value

JavaScript comparator functions make it straightforward to sort arrays of objects by a numeric property. const data = [ { name: 'Edward', order: 21 }, { name: 'Sharpe', order: 37 }, { name: 'And', order: 45 }, { name: 'The', order: -12 }, { name: 'Magnetic', order: 13 }, { name: 'Zeros', order: 37 }, ]; Descending Order const sorted = data.toSorted((a, b) => b.order - a.order); This places the largest order value first.

JavaScript Updated 07 Sep 2025 2 min read

Filter JavaScript Arrays Quickly and Clearly

Array.prototype.filter() creates a new array containing only the elements that satisfy a predicate. It does not modify the original array. Filter by a Condition const values = [1, 2, 3, 4, 5, 6]; const even = values.filter((value) => value % 2 === 0); console.log(even); // [2, 4, 6] Filter Objects by a Property const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, ]; const age25 = users.filter((user) => user.age === 25); Remove Duplicates For primitive values, a Set is usually clearer than using filter() with indexOf: